Search in sources :

Example 6 with OpenSearchTestCase

use of org.opensearch.test.OpenSearchTestCase in project OpenSearch by opensearch-project.

the class PeerFinderMessagesTests method testPeersResponseEqualsHashCodeSerialization.

public void testPeersResponseEqualsHashCodeSerialization() {
    final long initialTerm = randomNonNegativeLong();
    final PeersResponse initialPeersResponse;
    if (randomBoolean()) {
        initialPeersResponse = new PeersResponse(Optional.of(createNode(randomAlphaOfLength(10))), emptyList(), initialTerm);
    } else {
        initialPeersResponse = new PeersResponse(Optional.empty(), Arrays.stream(generateRandomStringArray(10, 10, false, false)).map(this::createNode).collect(Collectors.toList()), initialTerm);
    }
    // Note: the explicit cast of the CopyFunction is needed for some IDE (specifically Eclipse 4.8.0) to infer the right type
    EqualsHashCodeTestUtils.checkEqualsAndHashCode(initialPeersResponse, (CopyFunction<PeersResponse>) publishResponse -> copyWriteable(publishResponse, writableRegistry(), PeersResponse::new), in -> {
        final long term = in.getTerm();
        if (randomBoolean()) {
            return new PeersResponse(in.getMasterNode(), in.getKnownPeers(), randomValueOtherThan(term, OpenSearchTestCase::randomNonNegativeLong));
        } else {
            if (in.getMasterNode().isPresent()) {
                if (randomBoolean()) {
                    return new PeersResponse(Optional.of(createNode(randomAlphaOfLength(10))), in.getKnownPeers(), term);
                } else {
                    return new PeersResponse(Optional.empty(), singletonList(createNode(randomAlphaOfLength(10))), term);
                }
            } else {
                if (randomBoolean()) {
                    return new PeersResponse(Optional.of(createNode(randomAlphaOfLength(10))), emptyList(), term);
                } else {
                    return new PeersResponse(in.getMasterNode(), modifyDiscoveryNodesList(in.getKnownPeers(), false), term);
                }
            }
        }
    });
}
Also used : Arrays(java.util.Arrays) Collections.emptyList(java.util.Collections.emptyList) OpenSearchTestCase(org.opensearch.test.OpenSearchTestCase) Collection(java.util.Collection) Version(org.opensearch.Version) Collectors(java.util.stream.Collectors) ArrayList(java.util.ArrayList) Collections.singletonList(java.util.Collections.singletonList) DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) List(java.util.List) Optional(java.util.Optional) PeersResponse(org.opensearch.cluster.coordination.PeersResponse) EqualsHashCodeTestUtils(org.opensearch.test.EqualsHashCodeTestUtils) CopyFunction(org.opensearch.test.EqualsHashCodeTestUtils.CopyFunction) PeersResponse(org.opensearch.cluster.coordination.PeersResponse)

Example 7 with OpenSearchTestCase

use of org.opensearch.test.OpenSearchTestCase in project OpenSearch by opensearch-project.

the class GatewayMetaStatePersistedStateTests method testSetLastAcceptedStateTermChanged.

public void testSetLastAcceptedStateTermChanged() throws IOException {
    CoordinationState.PersistedState gateway = null;
    try {
        gateway = newGatewayPersistedState();
        final String indexName = randomAlphaOfLength(10);
        final int numberOfShards = randomIntBetween(1, 5);
        final long version = randomNonNegativeLong();
        final long term = randomValueOtherThan(Long.MAX_VALUE, OpenSearchTestCase::randomNonNegativeLong);
        final IndexMetadata indexMetadata = createIndexMetadata(indexName, numberOfShards, version);
        final ClusterState state = createClusterState(randomNonNegativeLong(), Metadata.builder().coordinationMetadata(createCoordinationMetadata(term)).put(indexMetadata, false).build());
        gateway.setLastAcceptedState(state);
        gateway = maybeNew(gateway);
        final long newTerm = randomLongBetween(term + 1, Long.MAX_VALUE);
        final int newNumberOfShards = randomValueOtherThan(numberOfShards, () -> randomIntBetween(1, 5));
        final IndexMetadata newIndexMetadata = createIndexMetadata(indexName, newNumberOfShards, version);
        final ClusterState newClusterState = createClusterState(randomNonNegativeLong(), Metadata.builder().coordinationMetadata(createCoordinationMetadata(newTerm)).put(newIndexMetadata, false).build());
        gateway.setLastAcceptedState(newClusterState);
        gateway = maybeNew(gateway);
        assertThat(gateway.getLastAcceptedState().metadata().index(indexName), equalTo(newIndexMetadata));
    } finally {
        IOUtils.close(gateway);
    }
}
Also used : ClusterState(org.opensearch.cluster.ClusterState) OpenSearchTestCase(org.opensearch.test.OpenSearchTestCase) CoordinationState(org.opensearch.cluster.coordination.CoordinationState) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata)

Example 8 with OpenSearchTestCase

use of org.opensearch.test.OpenSearchTestCase in project OpenSearch by opensearch-project.

the class InstallPluginCommandTests method testFailedSignatureVerification.

public void testFailedSignatureVerification() throws Exception {
    final String icu = "analysis-icu";
    final String url = "https://artifacts.opensearch.org/releases/plugins/analysis-icu/" + Version.CURRENT + "/" + icu + "-" + Build.CURRENT.getQualifiedVersion() + ".zip";
    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
    /*
         * To setup a situation where signature verification fails, we will mutate the input byte array by modifying a single byte to some
         * random byte value other than the actual value. This is enough to change the signature and cause verification to intentionally
         * fail.
         */
    final BiFunction<byte[], PGPSecretKey, String> signature = (b, p) -> {
        final byte[] bytes = Arrays.copyOf(b, b.length);
        bytes[0] = randomValueOtherThan(b[0], OpenSearchTestCase::randomByte);
        return signature(bytes, p);
    };
    final IllegalStateException e = expectThrows(IllegalStateException.class, () -> assertInstallPluginFromUrl(icu, icu, url, null, false, ".sha512", checksumAndFilename(digest, url), newSecretKey(), signature));
    assertThat(e, hasToString(equalTo("java.lang.IllegalStateException: signature verification for [" + url + "] failed")));
}
Also used : JcaPGPContentSignerBuilder(org.bouncycastle.openpgp.operator.jcajce.JcaPGPContentSignerBuilder) UserException(org.opensearch.cli.UserException) KeyPair(java.security.KeyPair) Matchers.hasToString(org.hamcrest.Matchers.hasToString) NoSuchFileException(java.nio.file.NoSuchFileException) Arrays(java.util.Arrays) ParametersFactory(com.carrotsearch.randomizedtesting.annotations.ParametersFactory) MockTerminal(org.opensearch.cli.MockTerminal) URL(java.net.URL) Date(java.util.Date) BiFunction(java.util.function.BiFunction) Matchers.not(org.hamcrest.Matchers.not) JcePBESecretKeyEncryptorBuilder(org.bouncycastle.openpgp.operator.jcajce.JcePBESecretKeyEncryptorBuilder) Version(org.opensearch.Version) Build(org.opensearch.Build) FileSystemUtils(org.opensearch.common.io.FileSystemUtils) DirectoryStream(java.nio.file.DirectoryStream) PGPKeyPair(org.bouncycastle.openpgp.PGPKeyPair) ByteArrayInputStream(java.io.ByteArrayInputStream) Locale(java.util.Locale) After(org.junit.After) HashAlgorithmTags(org.bouncycastle.bcpg.HashAlgorithmTags) URI(java.net.URI) PGPException(org.bouncycastle.openpgp.PGPException) Path(java.nio.file.Path) ZipEntry(java.util.zip.ZipEntry) PosixPermissionsResetter(org.opensearch.test.PosixPermissionsResetter) SimpleFileVisitor(java.nio.file.SimpleFileVisitor) KeyPairGenerator(java.security.KeyPairGenerator) SuppressForbidden(org.opensearch.common.SuppressForbidden) PathUtilsForTesting(org.opensearch.common.io.PathUtilsForTesting) PosixFileAttributes(java.nio.file.attribute.PosixFileAttributes) PosixFilePermission(java.nio.file.attribute.PosixFilePermission) PGPPrivateKey(org.bouncycastle.openpgp.PGPPrivateKey) OpenSearchTestCase(org.opensearch.test.OpenSearchTestCase) Set(java.util.Set) BouncyCastleFipsProvider(org.bouncycastle.jcajce.provider.BouncyCastleFipsProvider) PGPEncryptedData(org.bouncycastle.openpgp.PGPEncryptedData) PGPPublicKey(org.bouncycastle.openpgp.PGPPublicKey) Settings(org.opensearch.common.settings.Settings) PGPDigestCalculator(org.bouncycastle.openpgp.operator.PGPDigestCalculator) FileSystem(java.nio.file.FileSystem) Collectors(java.util.stream.Collectors) FileNotFoundException(java.io.FileNotFoundException) StandardCharsets(java.nio.charset.StandardCharsets) Matchers.startsWith(org.hamcrest.Matchers.startsWith) Tuple(org.opensearch.common.collect.Tuple) RegexMatcher.matches(org.opensearch.test.hamcrest.RegexMatcher.matches) PGPSecretKey(org.bouncycastle.openpgp.PGPSecretKey) FileVisitResult(java.nio.file.FileVisitResult) List(java.util.List) BCPGOutputStream(org.bouncycastle.bcpg.BCPGOutputStream) Stream(java.util.stream.Stream) Matchers.containsInAnyOrder(org.hamcrest.Matchers.containsInAnyOrder) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) LuceneTestCase(org.apache.lucene.util.LuceneTestCase) Matchers.containsString(org.hamcrest.Matchers.containsString) Matchers.endsWith(org.hamcrest.Matchers.endsWith) PathUtils(org.opensearch.common.io.PathUtils) ZipOutputStream(java.util.zip.ZipOutputStream) TestEnvironment(org.opensearch.env.TestEnvironment) ByteArrayOutputStream(java.io.ByteArrayOutputStream) MessageDigest(java.security.MessageDigest) CoreMatchers.equalTo(org.hamcrest.CoreMatchers.equalTo) PosixFileAttributeView(java.nio.file.attribute.PosixFileAttributeView) GroupPrincipal(java.nio.file.attribute.GroupPrincipal) JcaPGPDigestCalculatorProviderBuilder(org.bouncycastle.openpgp.operator.jcajce.JcaPGPDigestCalculatorProviderBuilder) Function(java.util.function.Function) StandardCopyOption(java.nio.file.StandardCopyOption) ArrayList(java.util.ArrayList) PGPSignatureGenerator(org.bouncycastle.openpgp.PGPSignatureGenerator) HashSet(java.util.HashSet) UserPrincipal(java.nio.file.attribute.UserPrincipal) Jimfs(com.google.common.jimfs.Jimfs) JcePBESecretKeyDecryptorBuilder(org.bouncycastle.openpgp.operator.jcajce.JcePBESecretKeyDecryptorBuilder) ExitCodes(org.opensearch.cli.ExitCodes) Before(org.junit.Before) Environment(org.opensearch.env.Environment) Terminal(org.opensearch.cli.Terminal) Matchers.empty(org.hamcrest.Matchers.empty) Configuration(com.google.common.jimfs.Configuration) MalformedURLException(java.net.MalformedURLException) Files(java.nio.file.Files) JcaPGPKeyPair(org.bouncycastle.openpgp.operator.jcajce.JcaPGPKeyPair) PGPSignature(org.bouncycastle.openpgp.PGPSignature) IOException(java.io.IOException) FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) ArmoredOutputStream(org.bouncycastle.bcpg.ArmoredOutputStream) MessageDigests(org.opensearch.common.hash.MessageDigests) StringReader(java.io.StringReader) BufferedReader(java.io.BufferedReader) NoSuchProviderException(java.security.NoSuchProviderException) Collections(java.util.Collections) InputStream(java.io.InputStream) OpenSearchTestCase(org.opensearch.test.OpenSearchTestCase) PGPSecretKey(org.bouncycastle.openpgp.PGPSecretKey) Matchers.hasToString(org.hamcrest.Matchers.hasToString) Matchers.containsString(org.hamcrest.Matchers.containsString) MessageDigest(java.security.MessageDigest)

Example 9 with OpenSearchTestCase

use of org.opensearch.test.OpenSearchTestCase in project OpenSearch by opensearch-project.

the class UpdateRequestTests method runTimeoutTest.

private void runTimeoutTest(final GetResult getResult, final UpdateRequest updateRequest) {
    final UpdateHelper.Result result = updateHelper.prepare(new ShardId("test", "", 0), updateRequest, getResult, OpenSearchTestCase::randomNonNegativeLong);
    final Writeable action = result.action();
    assertThat(action, instanceOf(ReplicationRequest.class));
    final ReplicationRequest<?> request = (ReplicationRequest<?>) action;
    assertThat(request.timeout(), equalTo(updateRequest.timeout()));
}
Also used : ShardId(org.opensearch.index.shard.ShardId) OpenSearchTestCase(org.opensearch.test.OpenSearchTestCase) ReplicationRequest(org.opensearch.action.support.replication.ReplicationRequest) Writeable(org.opensearch.common.io.stream.Writeable)

Example 10 with OpenSearchTestCase

use of org.opensearch.test.OpenSearchTestCase in project OpenSearch by opensearch-project.

the class RecoverySourceHandlerTests method generateOperations.

private static List<Translog.Operation> generateOperations(int numOps) {
    final List<Translog.Operation> operations = new ArrayList<>(numOps);
    final byte[] source = "{}".getBytes(StandardCharsets.UTF_8);
    final Set<Long> seqNos = new HashSet<>();
    for (int i = 0; i < numOps; i++) {
        final long seqNo = randomValueOtherThanMany(n -> seqNos.add(n) == false, OpenSearchTestCase::randomNonNegativeLong);
        final Translog.Operation op;
        if (randomBoolean()) {
            op = new Translog.Index("_doc", "id", seqNo, randomNonNegativeLong(), randomNonNegativeLong(), source, null, -1);
        } else if (randomBoolean()) {
            op = new Translog.Delete("_doc", "id", new Term("_id", Uid.encodeId("id")), seqNo, randomNonNegativeLong(), randomNonNegativeLong());
        } else {
            op = new Translog.NoOp(seqNo, randomNonNegativeLong(), "test");
        }
        operations.add(op);
    }
    return operations;
}
Also used : OpenSearchTestCase(org.opensearch.test.OpenSearchTestCase) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) Term(org.apache.lucene.index.Term) Translog(org.opensearch.index.translog.Translog) AtomicLong(java.util.concurrent.atomic.AtomicLong) HashSet(java.util.HashSet)

Aggregations

OpenSearchTestCase (org.opensearch.test.OpenSearchTestCase)10 ArrayList (java.util.ArrayList)3 HashSet (java.util.HashSet)3 IOException (java.io.IOException)2 Arrays (java.util.Arrays)2 Collections (java.util.Collections)2 EqualsHashCodeTestUtils (org.opensearch.test.EqualsHashCodeTestUtils)2 CopyFunction (org.opensearch.test.EqualsHashCodeTestUtils.CopyFunction)2 ParametersFactory (com.carrotsearch.randomizedtesting.annotations.ParametersFactory)1 Configuration (com.google.common.jimfs.Configuration)1 Jimfs (com.google.common.jimfs.Jimfs)1 BufferedReader (java.io.BufferedReader)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 FileNotFoundException (java.io.FileNotFoundException)1 InputStream (java.io.InputStream)1 StringReader (java.io.StringReader)1 MalformedURLException (java.net.MalformedURLException)1 URI (java.net.URI)1 URL (java.net.URL)1