|
| 1 | +/* |
| 2 | + * SPDX-License-Identifier: Apache-2.0 |
| 3 | + * |
| 4 | + * The OpenSearch Contributors require contributions made to |
| 5 | + * this file be licensed under the Apache-2.0 license or a |
| 6 | + * compatible open source license. |
| 7 | + */ |
| 8 | + |
| 9 | +package org.opensearch.common.round; |
| 10 | + |
| 11 | +import org.opensearch.test.OpenSearchTestCase; |
| 12 | + |
| 13 | +public class RoundableTests extends OpenSearchTestCase { |
| 14 | + |
| 15 | + public void testFloor() { |
| 16 | + int size = randomIntBetween(1, 256); |
| 17 | + long[] values = new long[size]; |
| 18 | + for (int i = 1; i < values.length; i++) { |
| 19 | + values[i] = values[i - 1] + (randomNonNegativeLong() % 200) + 1; |
| 20 | + } |
| 21 | + |
| 22 | + Roundable[] impls = { new BinarySearcher(values, size), new BidirectionalLinearSearcher(values, size) }; |
| 23 | + |
| 24 | + for (int i = 0; i < 100000; i++) { |
| 25 | + // Index of the expected round-down point. |
| 26 | + int idx = randomIntBetween(0, size - 1); |
| 27 | + |
| 28 | + // Value of the expected round-down point. |
| 29 | + long expected = values[idx]; |
| 30 | + |
| 31 | + // Delta between the expected and the next round-down point. |
| 32 | + long delta = (idx < size - 1) ? (values[idx + 1] - values[idx]) : 200; |
| 33 | + |
| 34 | + // Adding a random delta between 0 (inclusive) and delta (exclusive) to the expected |
| 35 | + // round-down point, which will still floor to the same value. |
| 36 | + long key = expected + (randomNonNegativeLong() % delta); |
| 37 | + |
| 38 | + for (Roundable roundable : impls) { |
| 39 | + assertEquals(expected, roundable.floor(key)); |
| 40 | + } |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + public void testFailureCases() { |
| 45 | + Throwable throwable; |
| 46 | + |
| 47 | + throwable = assertThrows(IllegalArgumentException.class, () -> new BinarySearcher(new long[0], 0)); |
| 48 | + assertEquals("at least one value must be present", throwable.getMessage()); |
| 49 | + throwable = assertThrows(IllegalArgumentException.class, () -> new BidirectionalLinearSearcher(new long[0], 0)); |
| 50 | + assertEquals("at least one value must be present", throwable.getMessage()); |
| 51 | + |
| 52 | + throwable = assertThrows(AssertionError.class, () -> new BinarySearcher(new long[] { 100 }, 1).floor(50)); |
| 53 | + assertEquals("key must be greater than or equal to 100", throwable.getMessage()); |
| 54 | + throwable = assertThrows(AssertionError.class, () -> new BidirectionalLinearSearcher(new long[] { 100 }, 1).floor(50)); |
| 55 | + assertEquals("key must be greater than or equal to 100", throwable.getMessage()); |
| 56 | + } |
| 57 | +} |
0 commit comments