index
int64
0
0
repo_id
stringlengths
26
205
file_path
stringlengths
51
246
content
stringlengths
8
433k
__index_level_0__
int64
0
10k
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/proxy/MyApi.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.proxy; import com.google.common.base.Preconditions; import com.netflix.titus.common.util.proxy.annotation.NoIntercept; import com.netflix.titus.common.util.proxy.annotation.ObservableResult; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import rx.Completable; import rx.Observable; @ObservableResult public interface MyApi { String echo(String message); @NoIntercept String notInterceptedEcho(String message); @ObservableResult Observable<String> observableEcho(String message); @ObservableResult Flux<String> fluxEcho(String message); @ObservableResult(enabled = false) Observable<String> untrackedObservableEcho(String message); Completable okCompletable(); Completable failingCompletable(); Mono<String> okMonoString(); Mono<String> failingMonoString(); Mono<Void> okMonoVoid(); class MyApiImpl implements MyApi { @Override public String echo(String message) { return buildReply(message); } @Override public String notInterceptedEcho(String message) { return echo(message); } @Override public Observable<String> observableEcho(String message) { return Observable.unsafeCreate(subscriber -> { subscriber.onNext(buildReply(message)); subscriber.onCompleted(); }); } @Override public Flux<String> fluxEcho(String message) { return Flux.create(emitter -> { emitter.next(buildReply(message)); emitter.complete(); }); } @Override public Observable<String> untrackedObservableEcho(String message) { return observableEcho(message); } @Override public Completable okCompletable() { return Completable.fromAction(() -> { // Do nothing }); } @Override public Completable failingCompletable() { return Completable.fromAction(() -> { throw new RuntimeException("simulated completable error"); }); } @Override public Mono<String> okMonoString() { return Mono.just("Hello"); } @Override public Mono<String> failingMonoString() { return Mono.fromRunnable(() -> { throw new RuntimeException("simulated completable error"); }); } @Override public Mono<Void> okMonoVoid() { return Mono.empty(); } String buildReply(String message) { Preconditions.checkNotNull(message); StringBuilder sb = new StringBuilder(); for (int i = 0; i < 100; i++) { sb.append(message); } return sb.toString(); } } }
500
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/proxy/LoggingProxyBuilderTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.proxy; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class LoggingProxyBuilderTest { @Test public void testCategoryDefaultsToInstanceIfInstanceNotProxy() throws Exception { MyApi proxy = ProxyCatalog.createGuardingProxy(MyApi.class, new MyApi.MyApiImpl(), () -> true); assertThat(LoggingProxyBuilder.getCategory(MyApi.class, proxy)).isEqualTo(MyApi.class); } @Test public void testCategoryDefaultsToApiIfInstanceIsProxy() throws Exception { assertThat(LoggingProxyBuilder.getCategory(MyApi.class, new MyApi.MyApiImpl())).isEqualTo(MyApi.MyApiImpl.class); } }
501
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/proxy
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/proxy/internal/GuardingInvocationHandlerTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.proxy.internal; import com.netflix.titus.common.util.proxy.MyApi; import com.netflix.titus.common.util.proxy.ProxyCatalog; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class GuardingInvocationHandlerTest { private static final String MESSAGE = "abcdefg"; private boolean flag; private final MyApi myApi = ProxyCatalog.createGuardingProxy(MyApi.class, new MyApi.MyApiImpl(), () -> flag); @Test(expected = IllegalStateException.class) public void testCallsToMethodsAreGuarded() throws Exception { myApi.echo(MESSAGE); } @Test public void testCallsToMethodsArePassedThrough() throws Exception { flag = true; assertThat(myApi.echo(MESSAGE)).startsWith(MESSAGE); } }
502
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/proxy
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/proxy/internal/SpectatorInvocationHandlerTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.proxy.internal; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.runtime.TitusRuntimes; import com.netflix.titus.common.util.proxy.MyApi; import com.netflix.titus.common.util.proxy.ProxyCatalog; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class SpectatorInvocationHandlerTest { private static final String MESSAGE = "abcdefg"; private final TitusRuntime titusRuntime = TitusRuntimes.test(); private final MyApi myApi = ProxyCatalog.createSpectatorProxy("myInstance", MyApi.class, new MyApi.MyApiImpl(), titusRuntime, true); @Test public void testSuccessfulMethodInvocation() { assertThat(myApi.echo("abc")).startsWith("abc"); } @Test(expected = NullPointerException.class) public void testFailedMethodInvocation() { myApi.echo(null); } @Test public void testObservableResult() { assertThat(myApi.observableEcho(MESSAGE).toBlocking().first()).startsWith(MESSAGE); } @Test(expected = NullPointerException.class) public void testFailedObservableResult() { assertThat(myApi.observableEcho(null).toBlocking().first()); } @Test public void testCompletable() { assertThat(myApi.okCompletable().get()).isNull(); } @Test public void testFailingCompletable() { assertThat(myApi.failingCompletable().get()).isInstanceOf(RuntimeException.class); } @Test public void testMonoString() { assertThat(myApi.okMonoString().block()).isEqualTo("Hello"); } @Test(expected = RuntimeException.class) public void testFailingMonoString() { myApi.failingMonoString().block(); } @Test public void testMonoVoid() { assertThat(myApi.okMonoVoid().block()).isNull(); } }
503
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/proxy
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/proxy/internal/InterceptingInvocationHandlerTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.proxy.internal; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.ArrayList; import java.util.List; import com.netflix.titus.common.util.proxy.MyApi; import org.junit.Test; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import rx.Completable; import rx.Observable; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; public class InterceptingInvocationHandlerTest { private enum InterceptionPoint {Before, After, AfterException, AfterObservable, AfterFlux, AfterCompletable, AfterMono} private static final String MESSAGE = "abcdefg"; private final TestableInterceptingInvocationHandler handler = new TestableInterceptingInvocationHandler(); private final MyApi myApi = (MyApi) Proxy.newProxyInstance( MyApi.class.getClassLoader(), new Class<?>[]{MyApi.class}, new InvocationHandlerBridge<>(handler, (MyApi) new MyApi.MyApiImpl()) ); @Test public void testSuccessfulMethodInvocation() { assertThat(myApi.echo(MESSAGE)).startsWith(MESSAGE); verifyInterceptionPointsCalled(InterceptionPoint.Before, InterceptionPoint.After); } @Test public void testFailedMethodInvocation() { try { myApi.echo(null); fail("Exception expected"); } catch (NullPointerException e) { verifyInterceptionPointsCalled(InterceptionPoint.Before, InterceptionPoint.AfterException); } } @Test public void testObservableResult() { assertThat(myApi.observableEcho(MESSAGE).toBlocking().first()).startsWith(MESSAGE); verifyInterceptionPointsCalled(InterceptionPoint.Before, InterceptionPoint.After, InterceptionPoint.AfterObservable); } @Test public void testFluxResult() { assertThat(myApi.fluxEcho(MESSAGE).blockFirst()).startsWith(MESSAGE); verifyInterceptionPointsCalled(InterceptionPoint.Before, InterceptionPoint.After, InterceptionPoint.AfterFlux); } @Test public void testFailedObservableResult() { try { myApi.observableEcho(null).toBlocking().first(); fail("Exception expected"); } catch (NullPointerException e) { verifyInterceptionPointsCalled(InterceptionPoint.Before, InterceptionPoint.After, InterceptionPoint.AfterObservable); } } @Test public void tesCompletableResult() { assertThat(myApi.okCompletable().get()).isNull(); verifyInterceptionPointsCalled(InterceptionPoint.Before, InterceptionPoint.After, InterceptionPoint.AfterCompletable); } @Test public void tesFailedCompletableResult() { assertThat(myApi.failingCompletable().get()).isInstanceOf(RuntimeException.class); verifyInterceptionPointsCalled(InterceptionPoint.Before, InterceptionPoint.After, InterceptionPoint.AfterCompletable); } @Test public void testMonoResult() { assertThat(myApi.okMonoString().block()).isEqualTo("Hello"); verifyInterceptionPointsCalled(InterceptionPoint.Before, InterceptionPoint.After, InterceptionPoint.AfterMono); } @Test public void tesFailedMonoResult() { try { myApi.failingMonoString().block(); fail("Mono failure expected"); } catch (Exception e) { assertThat(e).isInstanceOf(RuntimeException.class); } verifyInterceptionPointsCalled(InterceptionPoint.Before, InterceptionPoint.After, InterceptionPoint.AfterMono); } private void verifyInterceptionPointsCalled(InterceptionPoint... interceptionPoints) { assertThat(handler.interceptionPoints).hasSize(interceptionPoints.length); for (int i = 0; i < interceptionPoints.length; i++) { assertThat(handler.interceptionPoints.get(i)).isEqualTo(interceptionPoints[i]); } } private static class TestableInterceptingInvocationHandler extends InterceptingInvocationHandler<MyApi, Object, Boolean> { List<InterceptionPoint> interceptionPoints = new ArrayList<>(); TestableInterceptingInvocationHandler() { super(MyApi.class, false); } @Override protected Boolean before(Method method, Object[] args) { interceptionPoints.add(InterceptionPoint.Before); return true; } @Override protected void after(Method method, Object result, Boolean aBoolean) { interceptionPoints.add(InterceptionPoint.After); } @Override protected void afterException(Method method, Throwable cause, Boolean aBoolean) { interceptionPoints.add(InterceptionPoint.AfterException); } @Override protected Observable<Object> afterObservable(Method method, Observable<Object> result, Boolean aBoolean) { interceptionPoints.add(InterceptionPoint.AfterObservable); return result; } @Override protected Flux<Object> afterFlux(Method method, Flux<Object> result, Boolean aBoolean) { interceptionPoints.add(InterceptionPoint.AfterFlux); return result; } @Override protected Completable afterCompletable(Method method, Completable result, Boolean aBoolean) { interceptionPoints.add(InterceptionPoint.AfterCompletable); return result; } @Override protected Mono<Object> afterMono(Method method, Mono<Object> result, Boolean aBoolean) { interceptionPoints.add(InterceptionPoint.AfterMono); return result; } } }
504
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/proxy
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/proxy/internal/LoggingInvocationHandlerTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.proxy.internal; import com.netflix.titus.common.util.proxy.LoggingProxyBuilder; import com.netflix.titus.common.util.proxy.MyApi; import com.netflix.titus.common.util.proxy.ProxyCatalog; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class LoggingInvocationHandlerTest { private static final String MESSAGE = "abcdefg"; private final MyApi myApi = ProxyCatalog.createLoggingProxy(MyApi.class, new MyApi.MyApiImpl()) .request(LoggingProxyBuilder.Priority.INFO) .reply(LoggingProxyBuilder.Priority.INFO) .observableReply(LoggingProxyBuilder.Priority.INFO) .exception(LoggingProxyBuilder.Priority.INFO) .observableError(LoggingProxyBuilder.Priority.INFO) .build(); @Test public void testSuccessfulMethodInvocationLogging() { assertThat(myApi.echo(MESSAGE)).startsWith(MESSAGE); } @Test(expected = NullPointerException.class) public void testFailedMethodInvocationLogging() { myApi.echo(null); } @Test public void testObservableResultLogging() { assertThat(myApi.observableEcho(MESSAGE).toBlocking().first()).startsWith(MESSAGE); } @Test(expected = NullPointerException.class) public void testFailedObservableResultLogging() { myApi.observableEcho(null).toBlocking().first(); } @Test public void testCompletableResultLogging() { assertThat(myApi.okCompletable().get()).isNull(); } @Test public void testFailingCompletableResultLogging() { assertThat(myApi.failingCompletable().get()).isInstanceOf(RuntimeException.class); } @Test public void testMonoString() { assertThat(myApi.okMonoString().block()).isEqualTo("Hello"); } @Test(expected = RuntimeException.class) public void testFailingMonoString() { myApi.failingMonoString().block(); } @Test public void testMonoVoid() { assertThat(myApi.okMonoVoid().block()).isNull(); } }
505
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/retry
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/retry/internal/MaxManyRetryersTest.java
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.retry.internal; import java.util.concurrent.TimeUnit; import com.netflix.titus.common.util.retry.Retryer; import com.netflix.titus.common.util.retry.Retryers; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class MaxManyRetryersTest { @Test public void testMany() { // 10 / 1 (the expected delay of the first and the second retryer at this stage) Retryer first = Retryers.max( Retryers.interval(10, TimeUnit.MILLISECONDS, 4), Retryers.exponentialBackoff(1, 100, TimeUnit.MILLISECONDS) ); assertThat(first.getDelayMs()).contains(10L); // 10 / 2 Retryer second = first.retry(); assertThat(second.getDelayMs()).contains(10L); // 10 / 4 Retryer third = second.retry(); assertThat(third.getDelayMs()).contains(10L); // 10 / 8 Retryer fourth = third.retry(); assertThat(fourth.getDelayMs()).contains(10L); // 10 / 16 Retryer fifth = fourth.retry(); assertThat(fifth.getDelayMs()).contains(16L); // retry limit reached Retryer sixth = fifth.retry(); assertThat(sixth.getDelayMs()).isEmpty(); } @Test public void testClosed() { Retryer retryer = Retryers.max( Retryers.interval(10, TimeUnit.MILLISECONDS, 4), Retryers.never() ); assertThat(retryer.getDelayMs()).isEmpty(); } }
506
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/loadshedding
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/loadshedding/backoff/SimpleAdmissionBackoffStrategyTest.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.loadshedding.backoff; import java.util.concurrent.TimeUnit; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.runtime.TitusRuntimes; import com.netflix.titus.common.util.archaius2.Archaius2Ext; import com.netflix.titus.common.util.loadshedding.AdaptiveAdmissionController.ErrorKind; import org.junit.Test; import static com.jayway.awaitility.Awaitility.await; import static org.assertj.core.api.Assertions.assertThat; public class SimpleAdmissionBackoffStrategyTest { private final TitusRuntime titusRuntime = TitusRuntimes.internal(); @Test public void testBackoffRateLimited() { SimpleAdmissionBackoffStrategy backoff = new SimpleAdmissionBackoffStrategy("test", newConfiguration(), titusRuntime); assertThat(backoff.getThrottleFactor()).isEqualTo(1.0); // Unavailable backoff.onError(1, ErrorKind.RateLimited, null); await().until(() -> backoff.getThrottleFactor() <= 0.9); // Recovery testRecovery(backoff); } @Test public void testBackoffUnavailable() { SimpleAdmissionBackoffStrategy backoff = new SimpleAdmissionBackoffStrategy("test", newConfiguration(), titusRuntime); assertThat(backoff.getThrottleFactor()).isEqualTo(1.0); // Unavailable backoff.onError(1, ErrorKind.Unavailable, null); await().until(() -> backoff.getThrottleFactor() == 0.1); // Recovery testRecovery(backoff); } private void testRecovery(SimpleAdmissionBackoffStrategy backoff) { double factor = backoff.getThrottleFactor(); while (factor < 1.0) { backoff.onSuccess(1); double finalFactor = factor; await().pollDelay(1, TimeUnit.MILLISECONDS).until(() -> backoff.getThrottleFactor() > finalFactor); factor = backoff.getThrottleFactor(); } } private SimpleAdmissionBackoffStrategyConfiguration newConfiguration() { return Archaius2Ext.newConfiguration(SimpleAdmissionBackoffStrategyConfiguration.class, "monitoringIntervalMs", "1" ); } }
507
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/loadshedding
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/loadshedding/tokenbucket/TokenBucketAdmissionControllerTest.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.loadshedding.tokenbucket; import java.util.Arrays; import java.util.Collections; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.runtime.TitusRuntimes; import com.netflix.titus.common.util.loadshedding.AdmissionControllerRequest; import com.netflix.titus.common.util.loadshedding.AdmissionControllerResponse; import com.netflix.titus.common.util.loadshedding.AdmissionControllers; import org.junit.Test; import static com.netflix.titus.common.util.loadshedding.tokenbucket.TokenBucketTestConfigurations.NOT_SHARED_CONFIGURATION; import static com.netflix.titus.common.util.loadshedding.tokenbucket.TokenBucketTestConfigurations.SHARED_ANY_CONFIGURATION; import static com.netflix.titus.common.util.loadshedding.tokenbucket.TokenBucketTestConfigurations.SHARED_GETTERS_CONFIGURATION; import static org.assertj.core.api.Assertions.assertThat; public class TokenBucketAdmissionControllerTest { private final TitusRuntime titusRuntime = TitusRuntimes.internal(); @Test public void testSharedBucket() { TokenBucketAdmissionController controller = new TokenBucketAdmissionController( Collections.singletonList(SHARED_ANY_CONFIGURATION), AdmissionControllers.noBackoff(), true, titusRuntime ); AdmissionControllerRequest request = AdmissionControllerRequest.newBuilder() .withCallerId("any") .withEndpointName("any") .build(); // We assume the loop below will complete in a sec so we account for single refill only. int limit = SHARED_ANY_CONFIGURATION.getCapacity() + SHARED_ANY_CONFIGURATION.getRefillRateInSec() + 1; int stoppedAt = 0; while (stoppedAt < limit) { AdmissionControllerResponse response = controller.apply(request); if (!response.isAllowed()) { break; } stoppedAt++; } assertThat(stoppedAt).isGreaterThanOrEqualTo(SHARED_ANY_CONFIGURATION.getCapacity()); assertThat(stoppedAt).isLessThan(limit); } @Test public void testNotSharedBucket() { TokenBucketAdmissionController controller = new TokenBucketAdmissionController( Collections.singletonList(NOT_SHARED_CONFIGURATION), AdmissionControllers.noBackoff(), true, titusRuntime ); AdmissionControllerRequest user1Request = AdmissionControllerRequest.newBuilder() .withCallerId("myUser1") .withEndpointName("any") .build(); AdmissionControllerRequest user2Request = AdmissionControllerRequest.newBuilder() .withCallerId("myUser2") .withEndpointName("any") .build(); // We assume the loop below will complete in a sec so we account for single refill only. int limit = NOT_SHARED_CONFIGURATION.getCapacity() + NOT_SHARED_CONFIGURATION.getRefillRateInSec() + 1; int stoppedAt = 0; while (stoppedAt < limit) { AdmissionControllerResponse response1 = controller.apply(user1Request); AdmissionControllerResponse response2 = controller.apply(user2Request); if (response1.isAllowed() && response2.isAllowed()) { stoppedAt++; } else { break; } } assertThat(stoppedAt).isGreaterThanOrEqualTo(NOT_SHARED_CONFIGURATION.getCapacity()); assertThat(stoppedAt).isLessThan(limit); } @Test public void testOverlappingCallerIdButDifferentEndpointBuckets() { TokenBucketAdmissionController controller = new TokenBucketAdmissionController( Arrays.asList(SHARED_GETTERS_CONFIGURATION, SHARED_ANY_CONFIGURATION), AdmissionControllers.noBackoff(), true, titusRuntime ); AdmissionControllerRequest createRequest = AdmissionControllerRequest.newBuilder() .withCallerId("myUser") .withEndpointName("createX") .build(); AdmissionControllerRequest getRequest = AdmissionControllerRequest.newBuilder() .withCallerId("myUser") .withEndpointName("getX") .build(); AdmissionControllerResponse createResponse = controller.apply(createRequest); assertThat(createResponse.getReasonMessage()).contains(SHARED_ANY_CONFIGURATION.getName()); AdmissionControllerResponse getResponse = controller.apply(getRequest); assertThat(getResponse.getReasonMessage()).contains(SHARED_GETTERS_CONFIGURATION.getName()); } @Test public void testNoMatch() { TokenBucketAdmissionController controller = new TokenBucketAdmissionController( Collections.emptyList(), AdmissionControllers.noBackoff(), true, titusRuntime ); AdmissionControllerRequest request = AdmissionControllerRequest.newBuilder() .withCallerId("any") .withEndpointName("any") .build(); AdmissionControllerResponse response = controller.apply(request); assertThat(response.isAllowed()).isTrue(); assertThat(response.getReasonMessage()).isEqualTo("Rate limits not configured"); } }
508
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/loadshedding
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/loadshedding/tokenbucket/TokenBucketTestConfigurations.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.loadshedding.tokenbucket; import java.util.Map; import com.netflix.titus.common.util.CollectionsExt; class TokenBucketTestConfigurations { static Map<String, String> NOT_SHARED_PROPERTIES = CollectionsExt.asMap( "notShared.order", "10", "notShared.sharedByCallers", "false", "notShared.callerPattern", "myUser.*", "notShared.endpointPattern", ".*", "notShared.capacity", "5", "notShared.refillRateInSec", "1" ); static TokenBucketConfiguration NOT_SHARED_CONFIGURATION = new TokenBucketConfiguration( "notShared", 10, false, "myUser.*", ".*", 5, 1 ); static Map<String, String> NOT_SHARED_BAD_PROPERTIES = CollectionsExt.asMap("notShared.order", "abc"); static Map<String, String> SHARED_ANY_PROPERTIES = CollectionsExt.asMap( "sharedAny.order", "100", "sharedAny.sharedByCallers", "true", "sharedAny.callerPattern", ".*", "sharedAny.endpointPattern", ".*", "sharedAny.capacity", "10", "sharedAny.refillRateInSec", "2" ); static TokenBucketConfiguration SHARED_ANY_CONFIGURATION = new TokenBucketConfiguration( "sharedAny", 100, true, ".*", ".*", 10, 2 ); static TokenBucketConfiguration SHARED_GETTERS_CONFIGURATION = new TokenBucketConfiguration( "sharedGetters", 90, true, ".*", "get.*", 10, 2 ); static Map<String, String> SHARED_ANY_BAD_PROPERTIES = CollectionsExt.asMap( "sharedAny.order", "100" ); }
509
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/loadshedding
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/loadshedding/tokenbucket/ConfigurableTokenBucketAdmissionControllerTest.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.loadshedding.tokenbucket; import java.time.Duration; import java.util.List; import com.netflix.archaius.config.DefaultSettableConfig; import com.netflix.titus.common.framework.scheduler.model.ScheduleDescriptor; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.runtime.TitusRuntimes; import com.netflix.titus.common.util.Evaluators; import com.netflix.titus.common.util.loadshedding.AdaptiveAdmissionController; import com.netflix.titus.common.util.loadshedding.AdmissionController; import com.netflix.titus.common.util.loadshedding.AdmissionControllerRequest; import com.netflix.titus.common.util.loadshedding.AdmissionControllerResponse; import org.junit.After; import org.junit.Before; import org.junit.Test; import static com.jayway.awaitility.Awaitility.await; import static org.assertj.core.api.Assertions.assertThat; public class ConfigurableTokenBucketAdmissionControllerTest { private static final ScheduleDescriptor TEST_SCHEDULE_DESCRIPTOR = ConfigurableTokenBucketAdmissionController.SCHEDULE_DESCRIPTOR.toBuilder() .withInterval(Duration.ofMillis(1)) .build(); private final TitusRuntime titusRuntime = TitusRuntimes.internal(); private final DefaultSettableConfig config = new DefaultSettableConfig(); private ConfigurableTokenBucketAdmissionController controller; private volatile AdmissionControllerDelegateMock currentDelegate; @Before public void setUp() { this.controller = new ConfigurableTokenBucketAdmissionController( new ArchaiusTokenBucketAdmissionConfigurationParser(config), configuration -> currentDelegate = new AdmissionControllerDelegateMock(configuration), TEST_SCHEDULE_DESCRIPTOR, titusRuntime ); } @After public void tearDown() { Evaluators.acceptNotNull(controller, ConfigurableTokenBucketAdmissionController::close); } @Test public void testRefresh() { // Single configuration TokenBucketTestConfigurations.SHARED_ANY_PROPERTIES.forEach(config::setProperty); await().until(() -> currentDelegate != null); AdmissionControllerDelegateMock firstDelegate = currentDelegate; assertThat(firstDelegate.configuration).hasSize(1); // Two configuration rules TokenBucketTestConfigurations.NOT_SHARED_PROPERTIES.forEach(config::setProperty); await().until(() -> currentDelegate != firstDelegate); AdmissionControllerDelegateMock secondDelegate = currentDelegate; assertThat(secondDelegate.configuration).hasSize(2); } private static class AdmissionControllerDelegateMock implements AdaptiveAdmissionController { private final List<TokenBucketConfiguration> configuration; private AdmissionControllerDelegateMock(List<TokenBucketConfiguration> configuration) { this.configuration = configuration; } @Override public AdmissionControllerResponse apply(AdmissionControllerRequest request) { return AdmissionControllerResponse.newBuilder().build(); } @Override public void onSuccess(long elapsedMs) { } @Override public void onError(long elapsedMs, ErrorKind errorKind, Throwable cause) { } } }
510
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/loadshedding
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/loadshedding/tokenbucket/ArchaiusTokenBucketAdmissionConfigurationParserTest.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.loadshedding.tokenbucket; import java.util.HashMap; import java.util.List; import com.netflix.archaius.config.MapConfig; import com.netflix.titus.common.util.CollectionsExt; import org.junit.Test; import static com.netflix.titus.common.util.loadshedding.tokenbucket.TokenBucketTestConfigurations.SHARED_ANY_CONFIGURATION; import static com.netflix.titus.common.util.loadshedding.tokenbucket.TokenBucketTestConfigurations.SHARED_ANY_PROPERTIES; import static org.assertj.core.api.Assertions.assertThat; public class ArchaiusTokenBucketAdmissionConfigurationParserTest { @Test public void testNoConfiguration() { MapConfig config = new MapConfig(new HashMap<>()); ArchaiusTokenBucketAdmissionConfigurationParser parser = new ArchaiusTokenBucketAdmissionConfigurationParser(config); assertThat(parser.get()).isEmpty(); } @Test public void testValidConfiguration() { MapConfig config = new MapConfig(CollectionsExt.merge( TokenBucketTestConfigurations.NOT_SHARED_PROPERTIES, SHARED_ANY_PROPERTIES )); ArchaiusTokenBucketAdmissionConfigurationParser parser = new ArchaiusTokenBucketAdmissionConfigurationParser(config); List<TokenBucketConfiguration> configuration = parser.get(); assertThat(configuration).hasSize(2); assertThat(configuration.get(0)).isEqualTo(TokenBucketTestConfigurations.NOT_SHARED_CONFIGURATION); assertThat(configuration.get(1)).isEqualTo(TokenBucketTestConfigurations.SHARED_ANY_CONFIGURATION); } @Test public void testPartiallyInvalid() { MapConfig config = new MapConfig(CollectionsExt.merge( TokenBucketTestConfigurations.NOT_SHARED_BAD_PROPERTIES, SHARED_ANY_PROPERTIES )); ArchaiusTokenBucketAdmissionConfigurationParser parser = new ArchaiusTokenBucketAdmissionConfigurationParser(config); List<TokenBucketConfiguration> configuration = parser.get(); assertThat(configuration).hasSize(1); assertThat(configuration.get(0).getName()).isEqualTo(SHARED_ANY_CONFIGURATION.getName()); } @Test public void testAllInvalid() { MapConfig config = new MapConfig(CollectionsExt.merge( TokenBucketTestConfigurations.NOT_SHARED_BAD_PROPERTIES, TokenBucketTestConfigurations.SHARED_ANY_BAD_PROPERTIES )); ArchaiusTokenBucketAdmissionConfigurationParser parser = new ArchaiusTokenBucketAdmissionConfigurationParser(config); assertThat(parser.get()).isEmpty(); } }
511
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/loadshedding
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/loadshedding/tokenbucket/TokenBucketAdmissionControllerPerf.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.loadshedding.tokenbucket; import java.util.Arrays; import java.util.concurrent.TimeUnit; import com.google.common.base.Stopwatch; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.runtime.TitusRuntimes; import com.netflix.titus.common.util.loadshedding.AdmissionControllerRequest; import com.netflix.titus.common.util.loadshedding.AdmissionControllers; public class TokenBucketAdmissionControllerPerf { private static final TitusRuntime titusRuntime = TitusRuntimes.internal(); public static void main(String[] args) { long durationSec = 60; TokenBucketAdmissionController controller = new TokenBucketAdmissionController(Arrays.asList( newTokenBucketConfiguration("bucket1"), newTokenBucketConfiguration("bucket2") ), AdmissionControllers.noBackoff(), false, titusRuntime); Stopwatch stopwatch = Stopwatch.createStarted(); AdmissionControllerRequest bucket1Request = AdmissionControllerRequest.newBuilder() .withCallerId("bucket1") .withEndpointName("bucket1") .build(); AdmissionControllerRequest bucket2Request = AdmissionControllerRequest.newBuilder() .withCallerId("bucket2") .withEndpointName("bucket2") .build(); long allowed1 = 0; long rejected1 = 0; long allowed2 = 0; long rejected2 = 0; while (stopwatch.elapsed(TimeUnit.SECONDS) < durationSec) { if (controller.apply(bucket1Request).isAllowed()) { allowed1++; } else { rejected1++; } if (controller.apply(bucket2Request).isAllowed()) { allowed2++; } else { rejected2++; } } System.out.println("Allowed1 / sec: " + (allowed1 / durationSec)); System.out.println("Rejected1 / sec: " + (rejected1 / durationSec)); System.out.println("Allowed2 / sec: " + (allowed2 / durationSec)); System.out.println("Rejected2 / sec: " + (rejected2 / durationSec)); } private static TokenBucketConfiguration newTokenBucketConfiguration(String id) { return new TokenBucketConfiguration( id, 1, true, id + ".*", id + ".*", 2000, 1000 ); } }
512
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/limiter/tokenbucket
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/limiter/tokenbucket/internal/DefaultImmutableTokenBucketTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.limiter.tokenbucket.internal; import java.util.concurrent.TimeUnit; import com.netflix.titus.common.util.limiter.tokenbucket.ImmutableTokenBucket; import com.netflix.titus.common.util.time.Clocks; import com.netflix.titus.common.util.time.TestClock; import com.netflix.titus.common.util.tuple.Pair; import org.junit.Test; import static com.netflix.titus.common.util.limiter.ImmutableLimiters.refillAtFixedInterval; import static com.netflix.titus.common.util.limiter.ImmutableLimiters.tokenBucket; import static org.assertj.core.api.Assertions.assertThat; /** */ public class DefaultImmutableTokenBucketTest { private static final int BUCKET_SIZE = 5; private static final int REFILL_INTERVAL_MS = 100; private static final int REFILL_BATCH = 2; private final TestClock testClock = Clocks.test(); private final ImmutableTokenBucket tokenBucket = tokenBucket( BUCKET_SIZE, refillAtFixedInterval(REFILL_BATCH, REFILL_INTERVAL_MS, TimeUnit.MILLISECONDS, testClock) ); @Test public void testTryTake() throws Exception { ImmutableTokenBucket next = tokenBucket; for (int i = 0; i < BUCKET_SIZE; i++) { next = doTryTake(next); } assertThat(next.tryTake()).isEmpty(); // Advance time to refill the bucket testClock.advanceTime(REFILL_INTERVAL_MS, TimeUnit.MILLISECONDS); Pair<Long, ImmutableTokenBucket> pair = doTryTake(next, REFILL_BATCH, REFILL_BATCH); assertThat(pair.getLeft()).isEqualTo(REFILL_BATCH); assertThat(pair.getRight().tryTake()).isEmpty(); } @Test public void testTryTakeRange() throws Exception { Pair<Long, ImmutableTokenBucket> next = doTryTake(tokenBucket, 1, BUCKET_SIZE + 1); assertThat(next.getLeft()).isEqualTo(BUCKET_SIZE); assertThat(next.getRight().tryTake()).isEmpty(); testClock.advanceTime(10 * REFILL_INTERVAL_MS, TimeUnit.MILLISECONDS); next = doTryTake(next.getRight(), 1, BUCKET_SIZE + 1); assertThat(next.getLeft()).isEqualTo(BUCKET_SIZE); assertThat(next.getRight().tryTake()).isEmpty(); } private ImmutableTokenBucket doTryTake(ImmutableTokenBucket next) { next = next.tryTake().orElse(null); assertThat(next).describedAs("Expected more tokens in the bucket").isNotNull(); return next; } private Pair<Long, ImmutableTokenBucket> doTryTake(ImmutableTokenBucket next, int min, int max) { Pair<Long, ImmutableTokenBucket> pair = next.tryTake(min, max).orElse(null); assertThat(pair).describedAs("Expected more tokens in the bucket").isNotNull(); return pair; } }
513
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/limiter/tokenbucket
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/limiter/tokenbucket/internal/DefaultTokenBucketTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.limiter.tokenbucket.internal; import java.util.concurrent.TimeUnit; import com.netflix.titus.common.util.limiter.tokenbucket.RefillStrategy; import com.netflix.titus.common.util.limiter.tokenbucket.TokenBucket; import org.junit.Test; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class DefaultTokenBucketTest { @Test public void tryTakeShouldGetToken() { TestRefillStrategy testRefillStrategy = createTestRefillStrategy(); TokenBucket tokenBucket = createTokenBucket(10, testRefillStrategy, 0); testRefillStrategy.setAmountToRefill(1); boolean gotToken = tokenBucket.tryTake(); assertTrue(gotToken); testRefillStrategy.setAmountToRefill(10); gotToken = tokenBucket.tryTake(10); assertTrue(gotToken); } @Test public void tryTakeShouldNotGetToken() { TestRefillStrategy testRefillStrategy = createTestRefillStrategy(); TokenBucket tokenBucket = createTokenBucket(10, testRefillStrategy, 0); boolean gotToken = tokenBucket.tryTake(); assertFalse(gotToken); testRefillStrategy.setAmountToRefill(5); gotToken = tokenBucket.tryTake(6); assertFalse(gotToken); } @Test public void takeShouldGetToken() { TestRefillStrategy testRefillStrategy = createTestRefillStrategy(); TokenBucket tokenBucket = createTokenBucket(10, testRefillStrategy, 0); testRefillStrategy.setAmountToRefill(1); tokenBucket.take(); testRefillStrategy.setAmountToRefill(10); tokenBucket.take(10); } private static class TestRefillStrategy implements RefillStrategy { private final Object mutex = new Object(); private volatile long amountToRefill; private volatile long timeUntilNextRefill; @Override public long refill() { return amountToRefill; } @Override public long getTimeUntilNextRefill(TimeUnit unit) { return unit.convert(timeUntilNextRefill, TimeUnit.NANOSECONDS); } public void setAmountToRefill(long amountToRefill) { synchronized (mutex) { this.amountToRefill = amountToRefill; } } public void setTimeUntilNextRefill(long timeUntilNextRefill, TimeUnit unit) { synchronized (mutex) { this.timeUntilNextRefill = unit.toNanos(timeUntilNextRefill); } } } private TestRefillStrategy createTestRefillStrategy() { return new TestRefillStrategy(); } private TokenBucket createTokenBucket(long capacity, RefillStrategy refillStrategy, long initialNumberOfTokens) { return new DefaultTokenBucket("TestTokenBucket", capacity, refillStrategy, initialNumberOfTokens); } }
514
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/limiter/tokenbucket
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/limiter/tokenbucket/internal/FixedIntervalTokenBucketSupplierTest.java
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.limiter.tokenbucket.internal; import java.util.ArrayList; import java.util.List; import java.util.Optional; import com.netflix.archaius.api.config.SettableConfig; import com.netflix.archaius.config.DefaultSettableConfig; import com.netflix.titus.common.runtime.TitusRuntimes; import com.netflix.titus.common.util.archaius2.Archaius2Ext; import com.netflix.titus.common.util.limiter.tokenbucket.FixedIntervalTokenBucketConfiguration; import com.netflix.titus.common.util.limiter.tokenbucket.TokenBucket; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class FixedIntervalTokenBucketSupplierTest { private final SettableConfig settableConfig = new DefaultSettableConfig(); private final FixedIntervalTokenBucketConfiguration configuration = Archaius2Ext.newConfiguration( FixedIntervalTokenBucketConfiguration.class, "junit", settableConfig ); private final List<TokenBucket> buckets = new ArrayList<>(); private final FixedIntervalTokenBucketSupplier supplier = new FixedIntervalTokenBucketSupplier( "junit", configuration, buckets::add, Optional.of(TitusRuntimes.internal()) ); @Test public void testTokenBucketPersistsIfNotReconfigured() { settableConfig.setProperty("junit.initialNumberOfTokens", "1"); settableConfig.setProperty("junit.capacity", "1"); settableConfig.setProperty("junit.numberOfTokensPerInterval", "0"); TokenBucket tokenBucket = supplier.get(); assertThat(tokenBucket.tryTake()).isTrue(); assertThat(tokenBucket.tryTake()).isFalse(); tokenBucket.refill(1); assertThat(tokenBucket.tryTake()).isTrue(); assertThat(supplier.get() == tokenBucket).isTrue(); assertThat(buckets).hasSize(2); assertThat(buckets.get(1)).isEqualTo(tokenBucket); } @Test public void testTokenBucketIsRecreatedIfConfigurationChanges() { settableConfig.setProperty("junit.initialNumberOfTokens", "1"); settableConfig.setProperty("junit.capacity", "1"); settableConfig.setProperty("junit.numberOfTokensPerInterval", "0"); TokenBucket first = supplier.get(); assertThat(first.tryTake()).isTrue(); assertThat(first.tryTake()).isFalse(); settableConfig.setProperty("junit.initialNumberOfTokens", "2"); settableConfig.setProperty("junit.capacity", "2"); TokenBucket second = supplier.get(); assertThat(first != second).isTrue(); assertThat(second.tryTake()).isTrue(); assertThat(second.tryTake()).isTrue(); assertThat(second.tryTake()).isFalse(); assertThat(buckets).hasSize(3); assertThat(buckets.get(1)).isEqualTo(first); assertThat(buckets.get(2)).isEqualTo(second); } @Test public void testToString() { String text = supplier.get().toString(); assertThat(text).isEqualTo("DefaultTokenBucket{name='junit', capacity=1, refillStrategy=FixedIntervalRefillStrategy{refillRate=1.00 refill/s}, numberOfTokens=0}"); } }
515
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/limiter/tokenbucket
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/limiter/tokenbucket/internal/FixedIntervalRefillStrategyTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.limiter.tokenbucket.internal; import java.util.concurrent.TimeUnit; import com.netflix.titus.common.util.limiter.tokenbucket.RefillStrategy; import com.netflix.titus.common.util.time.Clocks; import com.netflix.titus.common.util.time.TestClock; import org.junit.Test; import static org.junit.Assert.assertEquals; public class FixedIntervalRefillStrategyTest { private final TestClock clock = Clocks.test(); @Test public void refillShouldReturn10() { RefillStrategy refillStrategy = new FixedIntervalRefillStrategy(1, 1, TimeUnit.SECONDS, clock); clock.advanceTime(9, TimeUnit.SECONDS); assertEquals(10, refillStrategy.refill()); } @Test public void timeUntilNextRefillShouldReturn1000() { RefillStrategy refillStrategy = new FixedIntervalRefillStrategy(1, 5, TimeUnit.SECONDS, clock); refillStrategy.refill(); long timeUntilNextRefill = refillStrategy.getTimeUntilNextRefill(TimeUnit.MILLISECONDS); assertEquals(5_000, timeUntilNextRefill); } }
516
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/grpc
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/grpc/reactor/SampleContextServerInterceptor.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.grpc.reactor; import java.util.Optional; import io.grpc.Context; import io.grpc.Contexts; import io.grpc.Metadata; import io.grpc.ServerCall; import io.grpc.ServerCallHandler; import io.grpc.ServerInterceptor; import io.grpc.stub.AbstractStub; import io.grpc.stub.MetadataUtils; public class SampleContextServerInterceptor implements ServerInterceptor { private static String CONTEXT_HEADER = "X-Titus-SimpleContext"; private static Metadata.Key<String> CONTEXT_KEY = Metadata.Key.of(CONTEXT_HEADER, Metadata.ASCII_STRING_MARSHALLER); private static Context.Key<SampleContext> CALLER_ID_CONTEXT_KEY = Context.key(CONTEXT_HEADER); public static final SampleContext CONTEXT_UNDEFINED = new SampleContext("undefined"); @Override public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) { String value = headers.get(CONTEXT_KEY); SampleContext context; if (value != null) { context = new SampleContext(value); } else { context = CONTEXT_UNDEFINED; } return Contexts.interceptCall(Context.current().withValue(CALLER_ID_CONTEXT_KEY, context), call, headers, next); } public static SampleContext serverResolve() { if (Context.current() == Context.ROOT) { return CONTEXT_UNDEFINED; } SampleContext context = CALLER_ID_CONTEXT_KEY.get(); return context == null ? CONTEXT_UNDEFINED : context; } public static <GRPC_STUB extends AbstractStub<GRPC_STUB>> GRPC_STUB attachClientContext(GRPC_STUB stub, Optional<SampleContext> contextOpt) { Metadata metadata = new Metadata(); metadata.put(CONTEXT_KEY, contextOpt.orElse(CONTEXT_UNDEFINED).getValue()); return stub.withInterceptors(MetadataUtils.newAttachHeadersInterceptor(metadata)); } }
517
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/grpc
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/grpc/reactor/SampleServiceReactorClient.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.grpc.reactor; import com.netflix.titus.testing.SampleGrpcService; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; public interface SampleServiceReactorClient { Mono<SampleGrpcService.SampleContainer> getOneValue(); Mono<SampleGrpcService.SampleContainer> getOneValue(SampleContext context); Mono<Void> setOneValue(SampleGrpcService.SampleContainer value); Mono<Void> setOneValue(SampleGrpcService.SampleContainer value, SampleContext context); Flux<SampleGrpcService.SampleContainer> stream(); Flux<SampleGrpcService.SampleContainer> stream(SampleContext context); }
518
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/grpc
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/grpc/reactor/SampleContext.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.grpc.reactor; import java.util.Objects; public class SampleContext { private final String value; public SampleContext(String value) { this.value = value; } public String getValue() { return value; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SampleContext that = (SampleContext) o; return Objects.equals(value, that.value); } @Override public int hashCode() { return Objects.hash(value); } @Override public String toString() { return "SampleContext{" + "value='" + value + '\'' + '}'; } }
519
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/grpc/reactor
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/grpc/reactor/server/ServerStreamingMethodHandlerTest.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.grpc.reactor.server; import io.grpc.stub.StreamObserver; import org.junit.Test; import reactor.core.Disposable; import reactor.core.publisher.DirectProcessor; import reactor.core.publisher.ReplayProcessor; import static org.assertj.core.api.Assertions.assertThat; public class ServerStreamingMethodHandlerTest { private final StreamObserver<String> responseObserver = new StreamObserver<String>() { @Override public void onNext(String value) { throw new RuntimeException("Simulated error"); } @Override public void onError(Throwable t) { } @Override public void onCompleted() { } }; @Test public void testOnNextExceptionHandlerOnSubscribe() { ReplayProcessor<String> publisher = ReplayProcessor.create(2); publisher.onNext("a"); publisher.onNext("b"); Disposable disposable = ServerStreamingMethodHandler.internalHandleResult(publisher, responseObserver); assertThat(disposable.isDisposed()).isTrue(); } @Test public void testOnNextExceptionHandlerAfterSubscribe() { DirectProcessor<String> publisher = DirectProcessor.create(); Disposable disposable = ServerStreamingMethodHandler.internalHandleResult(publisher, responseObserver); publisher.onNext("a"); publisher.onNext("b"); assertThat(disposable.isDisposed()).isTrue(); } }
520
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/grpc/reactor
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/grpc/reactor/server/GrpcToReactorServerBuilderTest.java
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.grpc.reactor.server; import java.time.Duration; import java.util.concurrent.TimeUnit; import java.util.stream.IntStream; import java.util.stream.Stream; import com.netflix.titus.common.util.ExceptionExt; import com.netflix.titus.common.util.grpc.reactor.SampleContext; import com.netflix.titus.common.util.grpc.reactor.SampleContextServerInterceptor; import com.netflix.titus.common.util.grpc.reactor.SampleServiceReactorClient; import com.netflix.titus.common.util.grpc.reactor.client.ReactorToGrpcClientBuilder; import com.netflix.titus.testing.SampleGrpcService.SampleContainer; import com.netflix.titus.testing.SampleServiceGrpc; import com.netflix.titus.testkit.rx.TitusRxSubscriber; import io.grpc.ManagedChannel; import io.grpc.Server; import io.grpc.ServerInterceptors; import io.grpc.ServerServiceDefinition; import io.grpc.netty.shaded.io.grpc.netty.NegotiationType; import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.springframework.aop.framework.ProxyFactory; import org.springframework.aop.support.AopUtils; import reactor.core.Disposable; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import static com.jayway.awaitility.Awaitility.await; import static org.assertj.core.api.Assertions.assertThat; public class GrpcToReactorServerBuilderTest { private static final long TIMEOUT_MS = 30_000; private static final Duration TIMEOUT_DURATION = Duration.ofMillis(TIMEOUT_MS); private static final SampleContainer HELLO = SampleContainer.newBuilder().setStringValue("Hello").build(); private static final SampleContext JUNIT_CONTEXT = new SampleContext("junitContext"); private ReactorSampleServiceImpl reactorSampleService; private ManagedChannel channel; private Server server; private SampleServiceReactorClient client; @Before public void setUp() throws Exception { createReactorGrpcServer(new ReactorSampleServiceImpl()); } @After public void tearDown() { ExceptionExt.silent(channel, ManagedChannel::shutdownNow); ExceptionExt.silent(server, Server::shutdownNow); } private void createReactorGrpcServer(ReactorSampleServiceImpl reactorSampleService) throws Exception { this.reactorSampleService = reactorSampleService; DefaultGrpcToReactorServerFactory<SampleContext> factory = new DefaultGrpcToReactorServerFactory<>(SampleContext.class, SampleContextServerInterceptor::serverResolve); ServerServiceDefinition serviceDefinition = factory.apply(SampleServiceGrpc.getServiceDescriptor(), reactorSampleService, ReactorSampleServiceImpl.class); this.server = NettyServerBuilder.forPort(0) .addService(ServerInterceptors.intercept(serviceDefinition, new SampleContextServerInterceptor())) .build() .start(); this.channel = NettyChannelBuilder.forTarget("localhost:" + server.getPort()) .negotiationType(NegotiationType.PLAINTEXT) .build(); this.client = ReactorToGrpcClientBuilder.newBuilder(SampleServiceReactorClient.class, SampleServiceGrpc.newStub(channel), SampleServiceGrpc.getServiceDescriptor(), SampleContext.class) .withTimeout(TIMEOUT_DURATION) .withStreamingTimeout(Duration.ofMillis(ReactorToGrpcClientBuilder.DEFAULT_STREAMING_TIMEOUT_MS)) .withGrpcStubDecorator(SampleContextServerInterceptor::attachClientContext) .build(); } @Test(timeout = 30_000) public void testMonoGet() { assertThat(client.getOneValue().block().getStringValue()).isEqualTo("Hello"); } @Test(timeout = 30_000) public void testMonoGetWithCallMetadata() { reactorSampleService.expectedContext = JUNIT_CONTEXT; assertThat(client.getOneValue(JUNIT_CONTEXT).block().getStringValue()).isEqualTo("Hello"); } @Test(timeout = 30_000) public void testMonoSet() { assertThat(client.setOneValue(HELLO).block()).isNull(); assertThat(reactorSampleService.lastSet).isEqualTo(HELLO); } @Test(timeout = 30_000) public void testMonoSetWithCallMetadata() { reactorSampleService.expectedContext = JUNIT_CONTEXT; assertThat(client.setOneValue(HELLO, JUNIT_CONTEXT).block()).isNull(); assertThat(reactorSampleService.lastSet).isEqualTo(HELLO); } @Test(timeout = 30_000) public void testFlux() throws InterruptedException { TitusRxSubscriber<SampleContainer> subscriber = new TitusRxSubscriber<>(); client.stream().subscribe(subscriber); checkTestFlux(subscriber); } @Test(timeout = 30_000) public void testFluxWithCallMetadata() throws InterruptedException { reactorSampleService.expectedContext = JUNIT_CONTEXT; TitusRxSubscriber<SampleContainer> subscriber = new TitusRxSubscriber<>(); client.stream(JUNIT_CONTEXT).subscribe(subscriber); checkTestFlux(subscriber); } private void checkTestFlux(TitusRxSubscriber<SampleContainer> subscriber) throws InterruptedException { assertThat(subscriber.takeNext(TIMEOUT_DURATION).getStringValue()).isEqualTo("Event1"); assertThat(subscriber.takeNext(TIMEOUT_DURATION).getStringValue()).isEqualTo("Event2"); assertThat(subscriber.takeNext(TIMEOUT_DURATION).getStringValue()).isEqualTo("Event3"); assertThat(subscriber.awaitClosed(TIMEOUT_DURATION)).isTrue(); assertThat(subscriber.hasError()).isFalse(); } @Test(timeout = 30_000) public void testMonoCancel() { reactorSampleService.block = true; testCancellation(client.getOneValue().subscribe()); } @Test(timeout = 30_000) public void testFluxStreamCancel() { reactorSampleService.block = true; testCancellation(client.stream().subscribe()); } @Test(timeout = 30_000) public void testAopCglibProxy() throws Exception { // Tear down the non-proxied server tearDown(); // Create proxied version of the service ReactorSampleServiceImpl reactorSampleServiceToProxy = new ReactorSampleServiceImpl(); ProxyFactory proxyFactory = new ProxyFactory(reactorSampleServiceToProxy); ReactorSampleServiceImpl proxy = (ReactorSampleServiceImpl) proxyFactory.getProxy(); assertThat(AopUtils.isCglibProxy(proxy)).isTrue(); // Create server with proxied service createReactorGrpcServer(proxy); assertThat(client.setOneValue(HELLO).block()).isNull(); assertThat(reactorSampleServiceToProxy.lastSet).isEqualTo(HELLO); } private void testCancellation(Disposable disposable) { await().timeout(TIMEOUT_MS, TimeUnit.MILLISECONDS).until(() -> reactorSampleService.requestTimestamp > 0); disposable.dispose(); await().timeout(TIMEOUT_MS, TimeUnit.MILLISECONDS).until(() -> reactorSampleService.cancelled); } public static class ReactorSampleServiceImpl { private long requestTimestamp; private SampleContainer lastSet; private volatile SampleContext expectedContext = SampleContextServerInterceptor.CONTEXT_UNDEFINED; private boolean block; private volatile boolean cancelled; public Mono<SampleContainer> getOneValue(SampleContext context) { checkContext(context); return block ? Mono.<SampleContainer>never().doOnCancel(() -> cancelled = true) : Mono.just(HELLO); } public Mono<Void> setOneValue(SampleContainer request, SampleContext context) { checkContext(context); this.lastSet = request; return block ? Mono.<Void>never().doOnCancel(() -> cancelled = true) : Mono.empty(); } public Flux<SampleContainer> stream(SampleContext context) { checkContext(context); if (block) { return Flux.<SampleContainer>never().doOnCancel(() -> cancelled = true); } Stream<SampleContainer> events = IntStream.of(1, 2, 3).mapToObj(i -> SampleContainer.newBuilder().setStringValue("Event" + i).build() ); return Flux.fromStream(events); } private void checkContext(SampleContext context) { requestTimestamp = System.currentTimeMillis(); assertThat(context).isEqualTo(expectedContext); } } }
521
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/grpc/reactor
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/grpc/reactor/client/ReactorToGrpcClientBuilderTest.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.grpc.reactor.client; import java.time.Duration; import java.util.concurrent.TimeUnit; import com.google.protobuf.Empty; import com.netflix.titus.common.util.ExceptionExt; import com.netflix.titus.common.util.grpc.reactor.SampleContext; import com.netflix.titus.common.util.grpc.reactor.SampleContextServerInterceptor; import com.netflix.titus.common.util.grpc.reactor.SampleServiceReactorClient; import com.netflix.titus.testing.SampleGrpcService.SampleContainer; import com.netflix.titus.testing.SampleServiceGrpc; import com.netflix.titus.testkit.rx.TitusRxSubscriber; import io.grpc.ManagedChannel; import io.grpc.Server; import io.grpc.ServerInterceptors; import io.grpc.netty.shaded.io.grpc.netty.NegotiationType; import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; import io.grpc.stub.ServerCallStreamObserver; import io.grpc.stub.StreamObserver; import org.junit.After; import org.junit.Before; import org.junit.Test; import reactor.core.Disposable; import static com.jayway.awaitility.Awaitility.await; import static org.assertj.core.api.Assertions.assertThat; public class ReactorToGrpcClientBuilderTest { private static final long TIMEOUT_MS = 30_000; private static final Duration TIMEOUT_DURATION = Duration.ofMillis(TIMEOUT_MS); private static final SampleContainer HELLO = SampleContainer.newBuilder().setStringValue("Hello").build(); private static final SampleContext JUNIT_CONTEXT = new SampleContext("junitContext"); private ManagedChannel channel; private Server server; private SampleServiceImpl sampleService; private SampleServiceReactorClient client; @Before public void setUp() throws Exception { this.sampleService = new SampleServiceImpl(); this.server = NettyServerBuilder.forPort(0) .addService(ServerInterceptors.intercept(sampleService, new SampleContextServerInterceptor())) .build() .start(); this.channel = NettyChannelBuilder.forTarget("localhost:" + server.getPort()) .negotiationType(NegotiationType.PLAINTEXT) .build(); this.client = ReactorToGrpcClientBuilder.newBuilder(SampleServiceReactorClient.class, SampleServiceGrpc.newStub(channel), SampleServiceGrpc.getServiceDescriptor(), SampleContext.class) .withTimeout(TIMEOUT_DURATION) .withStreamingTimeout(Duration.ofMillis(ReactorToGrpcClientBuilder.DEFAULT_STREAMING_TIMEOUT_MS)) .withGrpcStubDecorator(SampleContextServerInterceptor::attachClientContext) .build(); } @After public void tearDown() { ExceptionExt.silent(channel, ManagedChannel::shutdownNow); ExceptionExt.silent(server, Server::shutdownNow); } @Test(timeout = 30_000) public void testMonoGet() { assertThat(client.getOneValue().block().getStringValue()).isEqualTo("Hello"); } @Test(timeout = 30_000) public void testMonoGetWithCallMetadata() { sampleService.expectedContext = JUNIT_CONTEXT; assertThat(client.getOneValue(JUNIT_CONTEXT).block().getStringValue()).isEqualTo("Hello"); } @Test(timeout = 30_000) public void testMonoSet() { assertThat(client.setOneValue(HELLO).block()).isNull(); assertThat(sampleService.lastSet).isEqualTo(HELLO); } @Test(timeout = 30_000) public void testMonoSetWithCallMetadata() { sampleService.expectedContext = JUNIT_CONTEXT; assertThat(client.setOneValue(HELLO, JUNIT_CONTEXT).block()).isNull(); assertThat(sampleService.lastSet).isEqualTo(HELLO); } @Test(timeout = 30_000) public void testFlux() throws InterruptedException { TitusRxSubscriber<SampleContainer> subscriber = new TitusRxSubscriber<>(); client.stream().subscribe(subscriber); checkTestFlux(subscriber); } @Test(timeout = 30_000) public void testFluxWithCallMetadata() throws InterruptedException { sampleService.expectedContext = JUNIT_CONTEXT; TitusRxSubscriber<SampleContainer> subscriber = new TitusRxSubscriber<>(); client.stream(JUNIT_CONTEXT).subscribe(subscriber); checkTestFlux(subscriber); } private void checkTestFlux(TitusRxSubscriber<SampleContainer> subscriber) throws InterruptedException { assertThat(subscriber.takeNext(TIMEOUT_DURATION).getStringValue()).isEqualTo("Event1"); assertThat(subscriber.takeNext(TIMEOUT_DURATION).getStringValue()).isEqualTo("Event2"); assertThat(subscriber.takeNext(TIMEOUT_DURATION).getStringValue()).isEqualTo("Event3"); assertThat(subscriber.awaitClosed(TIMEOUT_DURATION)).isTrue(); assertThat(subscriber.hasError()).isFalse(); } @Test(timeout = 30_000) public void testMonoCancel() { sampleService.block = true; testCancellation(client.getOneValue().subscribe()); } @Test(timeout = 30_000) public void testFluxStreamCancel() { sampleService.block = true; testCancellation(client.stream().subscribe()); } private void testCancellation(Disposable disposable) { await().timeout(TIMEOUT_MS, TimeUnit.MILLISECONDS).until(() -> sampleService.requestTimestamp > 0); disposable.dispose(); await().timeout(TIMEOUT_MS, TimeUnit.MILLISECONDS).until(() -> sampleService.cancelled); } static class SampleServiceImpl extends SampleServiceGrpc.SampleServiceImplBase { private long requestTimestamp; private SampleContainer lastSet; private SampleContext expectedContext = SampleContextServerInterceptor.CONTEXT_UNDEFINED; private boolean block; private volatile boolean cancelled; @Override public void getOneValue(Empty request, StreamObserver<SampleContainer> responseObserver) { onRequest(responseObserver); if (!block) { responseObserver.onNext(HELLO); } } @Override public void setOneValue(SampleContainer request, StreamObserver<Empty> responseObserver) { onRequest(responseObserver); if (!block) { this.lastSet = request; responseObserver.onNext(Empty.getDefaultInstance()); responseObserver.onCompleted(); } } @Override public void stream(Empty request, StreamObserver<SampleContainer> responseObserver) { onRequest(responseObserver); if (!block) { for (int i = 1; i <= 3; i++) { responseObserver.onNext(SampleContainer.newBuilder().setStringValue("Event" + i).build()); } responseObserver.onCompleted(); } } private void onRequest(StreamObserver<?> responseObserver) { registerCancellationCallback(responseObserver); checkMetadata(); } private void registerCancellationCallback(StreamObserver<?> responseObserver) { ServerCallStreamObserver serverCallStreamObserver = (ServerCallStreamObserver) responseObserver; serverCallStreamObserver.setOnCancelHandler(() -> cancelled = true); } private void checkMetadata() { requestTimestamp = System.currentTimeMillis(); SampleContext context = SampleContextServerInterceptor.serverResolve(); assertThat(context).isEqualTo(expectedContext); } } }
522
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/guice
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/guice/internal/ActivationProvisionListenerTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.guice.internal; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import javax.inject.Singleton; import com.google.inject.AbstractModule; import com.netflix.governator.InjectorBuilder; import com.netflix.governator.LifecycleInjector; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.runtime.TitusRuntimes; import com.netflix.titus.common.util.guice.ActivationLifecycle; import com.netflix.titus.common.util.guice.ContainerEventBusModule; import com.netflix.titus.common.util.guice.annotation.Activator; import com.netflix.titus.common.util.guice.annotation.Deactivator; import com.netflix.titus.common.util.tuple.Pair; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class ActivationProvisionListenerTest { private final List<Pair<String, String>> activationTrace = new ArrayList<>(); @Test public void testActivationLifecycle() throws Exception { LifecycleInjector injector = InjectorBuilder.fromModules( new ContainerEventBusModule(), new AbstractModule() { @Override protected void configure() { bind(TitusRuntime.class).toInstance(TitusRuntimes.internal()); bind(ActivationProvisionListenerTest.class).toInstance(ActivationProvisionListenerTest.this); bind(ServiceA.class).asEagerSingleton(); } }).createInjector(); ActivationLifecycle activationLifecycle = injector.getInstance(ActivationLifecycle.class); ServiceA serviceA = injector.getInstance(ServiceA.class); assertThat(serviceA.state).isEqualTo("NOT_READY"); activationLifecycle.activate(); assertThat(activationLifecycle.isActive(serviceA)).isTrue(); assertThat(serviceA.state).isEqualTo("ACTIVATED"); activationLifecycle.deactivate(); assertThat(activationLifecycle.isActive(serviceA)).isFalse(); assertThat(serviceA.state).isEqualTo("DEACTIVATED"); } @Test public void testActivateOnlyOnce() throws Exception { LifecycleInjector injector = InjectorBuilder.fromModules( new ContainerEventBusModule(), new AbstractModule() { @Override protected void configure() { bind(TitusRuntime.class).toInstance(TitusRuntimes.internal()); bind(ActivationProvisionListenerTest.class).toInstance(ActivationProvisionListenerTest.this); bind(ServiceA.class); } }).createInjector(); ActivationLifecycle activationLifecycle = injector.getInstance(ActivationLifecycle.class); ServiceA serviceA = injector.getInstance(ServiceA.class); ServiceA otherServiceA = injector.getInstance(ServiceA.class); assertThat(serviceA).isSameAs(otherServiceA); assertThat(serviceA.state).isEqualTo("NOT_READY"); activationLifecycle.activate(); assertThat(activationLifecycle.isActive(serviceA)).isTrue(); assertThat(serviceA.state).isEqualTo("ACTIVATED"); assertThat(activationTrace).hasSize(1); activationLifecycle.deactivate(); assertThat(activationLifecycle.isActive(serviceA)).isFalse(); assertThat(serviceA.state).isEqualTo("DEACTIVATED"); assertThat(activationTrace).hasSize(2); } @Test public void testServiceReordering() throws Exception { LifecycleInjector injector = InjectorBuilder.fromModules( new ContainerEventBusModule(), new AbstractModule() { @Override protected void configure() { bind(TitusRuntime.class).toInstance(TitusRuntimes.internal()); bind(ActivationProvisionListenerTest.class).toInstance(ActivationProvisionListenerTest.this); bind(ServiceB.class).asEagerSingleton(); bind(ServiceA.class).asEagerSingleton(); } }).createInjector(); ActivationLifecycle activationLifecycle = injector.getInstance(ActivationLifecycle.class); activationLifecycle.activate(); assertThat(activationTrace).containsExactlyInAnyOrder( Pair.of("serviceA", "ACTIVATED"), Pair.of("serviceB", "ACTIVATED") ); } @Test public void testDeactivationOrderIsReverseOfActivation() throws Exception { LifecycleInjector injector = InjectorBuilder.fromModules( new ContainerEventBusModule(), new AbstractModule() { @Override protected void configure() { bind(TitusRuntime.class).toInstance(TitusRuntimes.internal()); bind(ActivationProvisionListenerTest.class).toInstance(ActivationProvisionListenerTest.this); bind(ServiceB.class).asEagerSingleton(); bind(ServiceA.class).asEagerSingleton(); } }).createInjector(); ActivationLifecycle activationLifecycle = injector.getInstance(ActivationLifecycle.class); activationLifecycle.activate(); activationLifecycle.deactivate(); assertThat(activationTrace).hasSize(4); String firstActivated = activationTrace.get(0).getLeft(); String secondActivated = activationTrace.get(1).getLeft(); assertThat(activationTrace.subList(2, 4)).containsExactly( Pair.of(secondActivated, "DEACTIVATED"), Pair.of(firstActivated, "DEACTIVATED") ); } @Singleton static class ServiceA { private final ActivationProvisionListenerTest owner; private volatile String state = "NOT_READY"; @Inject public ServiceA(ActivationProvisionListenerTest owner) { this.owner = owner; } @Activator public void activate() { state = "ACTIVATED"; owner.activationTrace.add(Pair.of("serviceA", state)); } @Deactivator public void deactivate() { state = "DEACTIVATED"; owner.activationTrace.add(Pair.of("serviceA", state)); } } @Singleton static class ServiceB { private final ActivationProvisionListenerTest owner; private volatile String state = "NOT_READY"; @Inject public ServiceB(ActivationProvisionListenerTest owner) { this.owner = owner; } @Activator public void activate() { state = "ACTIVATED"; owner.activationTrace.add(Pair.of("serviceB", state)); } @Deactivator public void deactivate() { state = "DEACTIVATED"; owner.activationTrace.add(Pair.of("serviceB", state)); } } }
523
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/guice
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/guice/internal/ProxyMethodInterceptorTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.guice.internal; import javax.inject.Singleton; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Provides; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.runtime.TitusRuntimes; import com.netflix.titus.common.util.guice.ActivationLifecycle; import com.netflix.titus.common.util.guice.ContainerEventBusModule; import com.netflix.titus.common.util.guice.ProxyType; import com.netflix.titus.common.util.guice.annotation.Activator; import com.netflix.titus.common.util.guice.annotation.ProxyConfiguration; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; public class ProxyMethodInterceptorTest { @Test public void testInterceptionWithSimpleBinding() throws Exception { doTest(new AbstractModule() { @Override protected void configure() { bind(MyService.class).to(MyServiceImpl.class); } }); } /** * Guice AOP works only with classes instantiated by Guice itself. This means that instances created with * providers, are not instrumented. This test exhibits this behavior. */ @Test(expected = AssertionError.class) public void testInterceptionDosNotWorkWithProviders() throws Exception { doTest(new MyModule()); } private void doTest(AbstractModule serviceModule) { Injector injector = Guice.createInjector( new ContainerEventBusModule(), new AbstractModule() { @Override protected void configure() { bind(TitusRuntime.class).toInstance(TitusRuntimes.internal()); } }, serviceModule ); MyServiceImpl service = (MyServiceImpl) injector.getInstance(MyService.class); // Check that service is guarded assertThat(service.isActive()).isFalse(); try { service.echo("hello"); fail("Expected to fail, as service is not activated yet"); } catch (Exception ignore) { } injector.getInstance(ActivationLifecycle.class).activate(); assertThat(service.isActive()).isTrue(); String reply = service.echo("hello"); assertThat(reply).isEqualTo("HELLO"); } interface MyService { String echo(String message); } @Singleton @ProxyConfiguration(types = {ProxyType.Logging, ProxyType.ActiveGuard}) static class MyServiceImpl implements MyService { private boolean active; @Activator public void activate() { this.active = true; } public boolean isActive() { return active; } @Override public String echo(String message) { return message.toUpperCase(); } } static class MyModule extends AbstractModule { @Override protected void configure() { } @Provides @Singleton public MyService getMyService() { return new MyServiceImpl(); } } }
524
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/code/SpectatorCodePointTrackerTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.code; import com.netflix.spectator.api.DefaultRegistry; import com.netflix.spectator.api.Registry; import com.netflix.titus.common.util.code.CodePointTracker.CodePoint; import org.junit.Before; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class SpectatorCodePointTrackerTest { private final Registry registry = new DefaultRegistry(); private final SpectatorCodePointTracker tracker = new SpectatorCodePointTracker(registry); @Before public void setUp() throws Exception { CodePointTracker.setDefault(tracker); } @Test public void testCodePointHit() throws Exception { tracker.markReachable(); tracker.markReachable("request2"); assertThat(tracker.marked).hasSize(2); for (CodePoint first : tracker.marked.keySet()) { assertThat(first.getClassName()).isEqualTo(SpectatorCodePointTrackerTest.class.getName()); assertThat(first.getMethodName()).isEqualTo("testCodePointHit"); } } @Test public void testCodePointHitViaStaticMethod() throws Exception { CodePointTracker.mark(); CodePointTracker.mark("request2"); assertThat(tracker.marked).hasSize(2); for (CodePoint first : tracker.marked.keySet()) { assertThat(first.getClassName()).isEqualTo(SpectatorCodePointTrackerTest.class.getName()); assertThat(first.getMethodName()).isEqualTo("testCodePointHitViaStaticMethod"); } } }
525
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/concurrency/CallbackCountDownLatchTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.concurrency; import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.junit.Assert; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; public class CallbackCountDownLatchTest { @Test public void zeroSizeIsValid() { final AtomicBoolean called = new AtomicBoolean(false); new CallbackCountDownLatch(0, () -> called.set(true)); Assert.assertTrue(called.get()); } @Test public void zeroCountDownTriggersCallback() { final AtomicInteger timesCalled = new AtomicInteger(0); final CallbackCountDownLatch latch = new CallbackCountDownLatch(2, timesCalled::getAndIncrement); assertThat(timesCalled).hasValue(0); latch.countDown(); assertThat(timesCalled).hasValue(0); latch.countDown(); assertThat(timesCalled).hasValue(1); // only called once latch.countDown(); assertThat(timesCalled).hasValue(1); } @Test public void asyncCallback() { final Executor mockExecutor = mock(Executor.class); final Runnable noop = () -> { }; final CallbackCountDownLatch latch = new CallbackCountDownLatch(2, noop, mockExecutor); verify(mockExecutor, never()).execute(any()); latch.countDown(); verify(mockExecutor, never()).execute(any()); latch.countDown(); verify(mockExecutor).execute(any()); // only called once latch.countDown(); verify(mockExecutor).execute(any()); } }
526
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/archaius2/Archaius2ObjectConfigurationResolverTest.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.archaius2; import com.netflix.archaius.api.annotations.DefaultValue; import com.netflix.archaius.config.DefaultSettableConfig; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class Archaius2ObjectConfigurationResolverTest { private final DefaultSettableConfig configuration = new DefaultSettableConfig(); private final ObjectConfigurationResolver<MyObject, MyObjectConfig> resolver = new Archaius2ObjectConfigurationResolver<>( configuration.getPrefixedView("object"), MyObject::getName, MyObjectConfig.class, Archaius2Ext.newConfiguration(MyObjectConfig.class, "default", configuration) ); @Test public void testDefaultObjectConfiguration() { assertThat(resolver.resolve(new MyObject("a")).getLimit()).isEqualTo(100); } @Test public void testDefaultOverrides() { configuration.setProperty("default.limit", "200"); assertThat(resolver.resolve(new MyObject("a")).getLimit()).isEqualTo(200); } @Test public void testObjectOverrides() { configuration.setProperty("object.a.pattern", "a"); configuration.setProperty("object.a.limit", "200"); configuration.setProperty("object.b.pattern", "b"); configuration.setProperty("object.b.limit", "300"); assertThat(resolver.resolve(new MyObject("a")).getLimit()).isEqualTo(200); assertThat(resolver.resolve(new MyObject("b")).getLimit()).isEqualTo(300); assertThat(resolver.resolve(new MyObject("x")).getLimit()).isEqualTo(100); } @Test public void testDynamicUpdates() { configuration.setProperty("object.a.pattern", "a"); configuration.setProperty("object.a.limit", "200"); assertThat(resolver.resolve(new MyObject("a")).getLimit()).isEqualTo(200); configuration.setProperty("object.a.limit", "300"); assertThat(resolver.resolve(new MyObject("a")).getLimit()).isEqualTo(300); configuration.clearProperty("object.a.pattern"); assertThat(resolver.resolve(new MyObject("a")).getLimit()).isEqualTo(100); } @Test public void testBadPattern() { configuration.setProperty("object.a.pattern", "a"); configuration.setProperty("object.a.limit", "200"); assertThat(resolver.resolve(new MyObject("a")).getLimit()).isEqualTo(200); configuration.setProperty("object.a.pattern", "*"); // bad regexp assertThat(resolver.resolve(new MyObject("a")).getLimit()).isEqualTo(200); } private static class MyObject { private final String name; MyObject(String name) { this.name = name; } String getName() { return name; } } private interface MyObjectConfig { @DefaultValue("100") int getLimit(); } }
527
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/archaius2/Archaius2ExtTest.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.archaius2; import java.time.Duration; import java.util.Collections; import java.util.Iterator; import com.netflix.archaius.DefaultPropertyFactory; import com.netflix.archaius.api.annotations.DefaultValue; import com.netflix.archaius.api.config.SettableConfig; import com.netflix.archaius.config.DefaultSettableConfig; import com.netflix.archaius.config.MapConfig; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class Archaius2ExtTest { @Test public void testAsDurationList() { assertThat(Archaius2Ext.asDurationList(() -> "1, 2, 3").get()).contains( Duration.ofMillis(1), Duration.ofMillis(2), Duration.ofMillis(3) ); } @Test public void testPropertyUpdate() { SettableConfig config = new DefaultSettableConfig(); config.setProperty("a", 1); DefaultPropertyFactory factory = new DefaultPropertyFactory(config); Iterator<Integer> it = Archaius2Ext.watch(factory, "a", Integer.class).toIterable().iterator(); assertThat(it.next()).isEqualTo(1); config.setProperty("a", 2); factory.invalidate(); assertThat(it.next()).isEqualTo(2); } @Test public void testConfiguration() { assertThat(Archaius2Ext.newConfiguration(MyConfig.class).getString()).isEqualTo("hello"); } @Test public void testConfigurationWithOverrides() { assertThat(Archaius2Ext.newConfiguration(MyConfig.class, "string", "overridden").getString()).isEqualTo("overridden"); } @Test public void testConfigurationWithNoPrefix() { MapConfig config = new MapConfig(Collections.singletonMap("string", "HELLO")); assertThat(Archaius2Ext.newConfiguration(MyConfig.class, config).getString()).isEqualTo("HELLO"); } @Test public void testConfigurationWithPrefix() { MapConfig config = new MapConfig(Collections.singletonMap("root.string", "HELLO")); assertThat(Archaius2Ext.newConfiguration(MyConfig.class, "root", config).getString()).isEqualTo("HELLO"); } private interface MyConfig { @DefaultValue("hello") String getString(); } }
528
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/archaius2/SpringConfigTest.java
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.archaius2; import org.junit.Test; import org.springframework.mock.env.MockEnvironment; import static org.assertj.core.api.Assertions.assertThat; public class SpringConfigTest { private final MockEnvironment environment = new MockEnvironment(); @Test public void testGetProperty() { environment.setProperty("number", "123"); SpringConfig config = new SpringConfig(null, environment); assertThat(config.getString("number")).isEqualTo("123"); assertThat(config.getLong("number")).isEqualTo(123L); } @Test public void testPrefixedView() { environment.setProperty("myPrefix.number", "123"); SpringConfig config = new SpringConfig("myPrefix", environment); assertThat(config.getString("number")).isEqualTo("123"); assertThat(config.getLong("number")).isEqualTo(123L); } @Test public void testUpdates() { environment.setProperty("number", "123"); SpringConfig config = new SpringConfig(null, environment); assertThat(config.getString("number")).isEqualTo("123"); assertThat(config.getLong("number")).isEqualTo(123L); environment.setProperty("number", "456"); assertThat(config.getString("number")).isEqualTo("456"); assertThat(config.getLong("number")).isEqualTo(456L); } }
529
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/archaius2/ArchaiusProxyInvocationHandlerTest.java
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.archaius2; import java.time.Duration; import java.util.Arrays; import java.util.List; import java.util.Set; import com.netflix.archaius.api.annotations.Configuration; import com.netflix.archaius.api.annotations.DefaultValue; import com.netflix.archaius.api.annotations.PropertyName; import com.netflix.titus.common.environment.MyEnvironments; import com.netflix.titus.common.environment.MyMutableEnvironment; import com.netflix.titus.common.util.CollectionsExt; import org.junit.Before; import org.junit.Test; import static com.jayway.awaitility.Awaitility.await; import static org.assertj.core.api.Assertions.assertThat; public class ArchaiusProxyInvocationHandlerTest { private final MyMutableEnvironment environment = MyEnvironments.newMutable(); private SomeConfiguration configuration; @Before public void setUp() { environment.setProperty("annotationPrefix.intWithNoDefault", "11"); this.configuration = Archaius2Ext.newConfiguration(SomeConfiguration.class, environment); } @Test public void testInt() { assertThat(configuration.getInt()).isEqualTo(1); environment.setProperty("annotationPrefix.int", "123"); await().until(() -> configuration.getInt() == 123); assertThat(configuration.getIntWithNoDefault()).isEqualTo(11); } @Test public void testLong() { assertThat(configuration.getLong()).isEqualTo(2L); environment.setProperty("annotationPrefix.long", "123"); await().until(() -> configuration.getLong() == 123); } @Test public void testDouble() { assertThat(configuration.getDouble()).isEqualTo(3.3D); environment.setProperty("annotationPrefix.double", "4.4"); await().until(() -> configuration.getDouble() == 4.4); } @Test public void testFloat() { assertThat(configuration.getFloat()).isEqualTo(4.5F); environment.setProperty("annotationPrefix.float", "5.5"); await().until(() -> configuration.getFloat() == 5.5F); } @Test public void testBoolean() { assertThat(configuration.getBoolean()).isTrue(); environment.setProperty("annotationPrefix.boolean", "false"); await().until(() -> !configuration.getBoolean()); } @Test public void testDuration() { assertThat(configuration.getDuration()).isEqualTo(Duration.ofSeconds(60)); environment.setProperty("annotationPrefix.duration", "24h"); assertThat(configuration.getDuration()).isEqualTo(Duration.ofDays(1)); } @Test public void testList() { assertThat(configuration.getList()).containsExactly("a", "b", "c"); environment.setProperty("annotationPrefix.list", "A,B,C"); List<String> expected = Arrays.asList("A", "B", "C"); await().until(() -> configuration.getList().equals(expected)); } @Test public void testEmptyList() { assertThat(configuration.getEmptyList()).isEmpty(); } @Test public void testSet() { assertThat(configuration.getSet()).containsExactly("d", "e", "f"); environment.setProperty("annotationPrefix.set", "D,E,F"); Set<String> expected = CollectionsExt.asSet("D", "E", "F"); await().until(() -> configuration.getSet().containsAll(expected)); } @Test public void testEmptySet() { assertThat(configuration.getEmptySet()).isEmpty(); } @Test public void testNullValue() { assertThat(configuration.getInteger()).isNull(); environment.setProperty("annotationPrefix.integer", "1"); await().until(() -> configuration.getInteger() != null && configuration.getInteger() == 1); } @Test(expected = IllegalArgumentException.class) public void testCreateFailsOnPropertiesWithoutValue() { Archaius2Ext.newConfiguration(SomeConfiguration.class, MyEnvironments.newMutable()); } @Test public void testCustomPrefix() { environment.setProperty("customPrefix.intWithNoDefault", "456"); SomeConfiguration configuration = Archaius2Ext.newConfiguration(SomeConfiguration.class, "customPrefix", environment); assertThat(configuration.getIntWithNoDefault()).isEqualTo(456); } @Test public void testDefaultMethods() { assertThat(configuration.getNumber(false)).isEqualTo(1); assertThat(configuration.getNumber(true)).isEqualTo(2); } @Test public void testPropertyNameOverride() { assertThat(configuration.getMyStrangeName()).isEqualTo("strangeDefault"); environment.setProperty("annotationPrefix.my.strange.name", "abc"); assertThat(configuration.getMyStrangeName()).isEqualTo("abc"); } @Test public void testToString() { String[] expectedParts = {"float=4.5", "boolean=true", "double=3.3", "intWithNoDefault=11", "list=[a, b, c]", "set=[d, e, f]", "int=1", "long=2"}; String actual = configuration.toString(); for (String part : expectedParts) { assertThat(actual).contains(part); } } @Configuration(prefix = "annotationPrefix") private interface SomeConfiguration { @DefaultValue("1") int getInt(); Integer getInteger(); int getIntWithNoDefault(); @DefaultValue("2") long getLong(); @DefaultValue("3.3") double getDouble(); @DefaultValue("4.5") double getFloat(); @DefaultValue("true") boolean getBoolean(); @DefaultValue("60s") Duration getDuration(); @DefaultValue("a,b,c") List<String> getList(); List<String> getEmptyList(); @DefaultValue("d,e,f") List<String> getSet(); Set<String> getEmptySet(); @DefaultValue("strangeDefault") @PropertyName(name = "my.strange.name") String getMyStrangeName(); default long getNumber(boolean returnLong) { return returnLong ? getLong() : getInt(); } } }
530
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/archaius2/PeriodicallyRefreshingObjectConfigurationResolverTest.java
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.archaius2; import com.netflix.archaius.api.annotations.DefaultValue; import com.netflix.titus.common.environment.MyEnvironment; import com.netflix.titus.common.environment.MyEnvironments; import com.netflix.titus.common.util.closeable.CloseableReference; import org.junit.After; import org.junit.Test; import org.springframework.mock.env.MockEnvironment; import reactor.core.publisher.DirectProcessor; import static org.assertj.core.api.Assertions.assertThat; public class PeriodicallyRefreshingObjectConfigurationResolverTest { private final MockEnvironment configuration = new MockEnvironment(); private final DirectProcessor<Long> updateTrigger = DirectProcessor.create(); private final CloseableReference<ObjectConfigurationResolver<MyObject, MyObjectConfig>> resolverRef = Archaius2Ext.newObjectConfigurationResolver( "object", configuration, MyObject::getName, MyObjectConfig.class, Archaius2Ext.newConfiguration(MyObjectConfig.class, "default", MyEnvironments.newSpring(configuration)), updateTrigger ); private final ObjectConfigurationResolver<MyObject, MyObjectConfig> resolver = resolverRef.get(); @After public void tearDown() { resolverRef.close(); } @Test public void testDefaultObjectConfiguration() { assertThat(resolver.resolve(new MyObject("a")).getLimit()).isEqualTo(100); } @Test public void testDefaultOverrides() { update("default.limit", "200"); assertThat(resolver.resolve(new MyObject("a")).getLimit()).isEqualTo(200); } @Test public void testObjectOverrides() { update("object.a.pattern", "a", "object.a.limit", "200", "object.b.pattern", "b", "object.b.limit", "300" ); assertThat(resolver.resolve(new MyObject("a")).getLimit()).isEqualTo(200); assertThat(resolver.resolve(new MyObject("b")).getLimit()).isEqualTo(300); assertThat(resolver.resolve(new MyObject("x")).getLimit()).isEqualTo(100); } @Test public void testDynamicUpdates() { update("object.a.pattern", "a", "object.a.limit", "200" ); assertThat(resolver.resolve(new MyObject("a")).getLimit()).isEqualTo(200); update("object.a.limit", "300"); assertThat(resolver.resolve(new MyObject("a")).getLimit()).isEqualTo(300); update("object.a.pattern", "not_a_anymore"); assertThat(resolver.resolve(new MyObject("a")).getLimit()).isEqualTo(100); } @Test public void testBadPattern() { update("object.a.pattern", "a", "object.a.limit", "200" ); assertThat(resolver.resolve(new MyObject("a")).getLimit()).isEqualTo(200); update("object.a.pattern", "*"); // bad regexp assertThat(resolver.resolve(new MyObject("a")).getLimit()).isEqualTo(200); } private void update(String... keyValuePairs) { for (int i = 0; i < keyValuePairs.length; i += 2) { configuration.setProperty(keyValuePairs[i], keyValuePairs[i + 1]); } updateTrigger.onNext(System.currentTimeMillis()); } private static class MyObject { private final String name; MyObject(String name) { this.name = name; } String getName() { return name; } } private interface MyObjectConfig { @DefaultValue("100") int getLimit(); } }
531
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/feature/FeatureGuardWithPredicatesTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.feature; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Predicate; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class FeatureGuardWithPredicatesTest { @Test public void testWhiteList() { Predicate<String> featureGuard = FeatureGuards.toPredicate(FeatureGuards.newWhiteList() .withTurnOnPredicate(() -> true) .withWhiteListRegExpSupplier("whiteList", () -> "enabled.*") .withBlackListRegExpSupplier("blackList", () -> "disabled.*") .build() ); assertThat(featureGuard.test("enabledABC")).isTrue(); assertThat(featureGuard.test("disabledABC")).isFalse(); assertThat(featureGuard.test("unmatched")).isFalse(); } @Test public void testDynamicTurnOff() { AtomicBoolean turnOnRef = new AtomicBoolean(true); Predicate<String> featureGuard = FeatureGuards.toPredicate(FeatureGuards.newWhiteList() .withTurnOnPredicate(turnOnRef::get) .withWhiteListRegExpSupplier("whiteList", () -> "enabled.*") .build() ); assertThat(featureGuard.test("enabledABC")).isTrue(); turnOnRef.set(false); assertThat(featureGuard.test("enabledABC")).isFalse(); } @Test public void testDynamicWhiteListUpdate() { AtomicReference<String> whiteListRef = new AtomicReference<>("enabled.*"); Predicate<String> featureGuard = FeatureGuards.toPredicate(FeatureGuards.newWhiteList() .withTurnOnPredicate(() -> true) .withWhiteListRegExpSupplier("whiteList", whiteListRef::get) .build() ); assertThat(featureGuard.test("enabledABC")).isTrue(); whiteListRef.set("enabledDEF"); assertThat(featureGuard.test("enabledABC")).isFalse(); } @Test public void testConfiguration() { FeatureGuardWhiteListConfiguration configuration = new FeatureGuardWhiteListConfiguration() { @Override public boolean isFeatureEnabled() { return true; } @Override public String getWhiteList() { return "enabled.*"; } @Override public String getBlackList() { return "disabled.*"; } }; Predicate<String> featureGuard = FeatureGuards.toPredicate(FeatureGuards.newWhiteListFromConfiguration(configuration).build()); assertThat(featureGuard.test("enabledABC")).isTrue(); assertThat(featureGuard.test("disabledABC")).isFalse(); assertThat(featureGuard.test("unmatched")).isFalse(); } }
532
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/feature/FeatureGuardForMapTest.java
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.feature; import java.util.Map; import java.util.function.Function; import com.netflix.titus.common.util.CollectionsExt; import com.netflix.titus.common.util.feature.FeatureGuard.FeatureGuardResult; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class FeatureGuardForMapTest { private static final Map<String, String> ATTRIBUTES = CollectionsExt.asMap( "key1", "value1", "key2", "value2", "keyWithEmptyValue", "", "keyWithNullValue", null ); @Test public void testKeyValueMatcherWhiteList() { assertThat(testWhiteListMatcher("key1=value1")).isEqualTo(FeatureGuardResult.Approved); assertThat(testWhiteListMatcher("key1=.*")).isEqualTo(FeatureGuardResult.Approved); assertThat(testWhiteListMatcher("key2=.*")).isEqualTo(FeatureGuardResult.Approved); assertThat(testWhiteListMatcher("key(1|2)=value.*")).isEqualTo(FeatureGuardResult.Approved); assertThat(testWhiteListMatcher("keyWithEmptyValue=")).isEqualTo(FeatureGuardResult.Approved); assertThat(testWhiteListMatcher("keyWithNullValue=")).isEqualTo(FeatureGuardResult.Approved); } @Test public void testKeyValueMatcherBlackList() { assertThat(testBlackListMatcher("key1=value1")).isEqualTo(FeatureGuardResult.Denied); assertThat(testBlackListMatcher("keyWithEmptyValue=")).isEqualTo(FeatureGuardResult.Denied); assertThat(testBlackListMatcher("keyWithNullValue=")).isEqualTo(FeatureGuardResult.Denied); } private FeatureGuardResult testWhiteListMatcher(String whiteList) { return FeatureGuards.fromMap(Function.identity(), FeatureGuards.newWhiteList() .withTurnOnPredicate(() -> true) .withWhiteListRegExpSupplier("jobDescriptor.attributes", () -> whiteList) .withBlackListRegExpSupplier("jobDescriptor.attributes", () -> "NONE") .build() ).matches(ATTRIBUTES); } private FeatureGuardResult testBlackListMatcher(String blackList) { return FeatureGuards.fromMap(Function.identity(), FeatureGuards.newWhiteList() .withTurnOnPredicate(() -> true) .withWhiteListRegExpSupplier("jobDescriptor.attributes", () -> "NONE") .withBlackListRegExpSupplier("jobDescriptor.attributes", () -> blackList) .build() ).matches(ATTRIBUTES); } }
533
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/feature/FeatureGuardsTest.java
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.feature; import org.junit.Test; import static com.netflix.titus.common.util.feature.FeatureGuards.alwaysApproved; import static com.netflix.titus.common.util.feature.FeatureGuards.alwaysDenied; import static com.netflix.titus.common.util.feature.FeatureGuards.alwaysUndecided; import static com.netflix.titus.common.util.feature.FeatureGuards.toPredicate; import static org.assertj.core.api.Assertions.assertThat; public class FeatureGuardsTest { @Test public void testPredicates() { assertThat(toPredicate().test("anything")).isFalse(); assertThat(toPredicate(alwaysApproved()).test("anything")).isTrue(); assertThat(toPredicate(alwaysDenied()).test("anything")).isFalse(); assertThat(toPredicate(alwaysUndecided()).test("anything")).isFalse(); assertThat(toPredicate(alwaysUndecided(), alwaysUndecided()).test("anything")).isFalse(); assertThat(toPredicate(alwaysUndecided(), alwaysApproved()).test("anything")).isTrue(); assertThat(toPredicate(alwaysUndecided(), alwaysDenied()).test("anything")).isFalse(); assertThat(toPredicate(alwaysApproved(), alwaysDenied()).test("anything")).isTrue(); assertThat(toPredicate(alwaysDenied(), alwaysApproved()).test("anything")).isFalse(); } }
534
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/spectator/SpectatorExtTest.java
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.spectator; import java.util.concurrent.atomic.AtomicInteger; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class SpectatorExtTest { @Test public void testUniqueTagValue() { assertThat(SpectatorExt.uniqueTagValue("testBase", value -> false)).isEqualTo("testBase"); assertThat(SpectatorExt.uniqueTagValue("testBase", value -> value.equals("testBase"))).startsWith("testBase#"); AtomicInteger counter = new AtomicInteger(); assertThat(SpectatorExt.uniqueTagValue("testBase", value -> counter.incrementAndGet() < 5)).startsWith("testBase#"); assertThat(counter).hasValue(5); String longValue = buildLongValue(); assertThat(SpectatorExt.uniqueTagValue(longValue, value -> false)).hasSize(SpectatorExt.MAX_TAG_VALUE_LENGTH); assertThat(SpectatorExt.uniqueTagValue(longValue, value -> !value.contains("#"))).hasSize(SpectatorExt.MAX_TAG_VALUE_LENGTH); } private String buildLongValue() { StringBuilder longValueBuilder = new StringBuilder(); for (int i = 0; i < SpectatorExt.MAX_TAG_VALUE_LENGTH; i++) { longValueBuilder.append("X"); } return longValueBuilder.append("END").toString(); } }
535
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/spectator/MultiDimensionalGaugeTest.java
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.spectator; import java.util.Collections; import java.util.List; import com.netflix.spectator.api.DefaultRegistry; import com.netflix.spectator.api.Gauge; import com.netflix.spectator.api.Id; import com.netflix.spectator.api.Registry; import org.junit.Test; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; public class MultiDimensionalGaugeTest { private final Registry registry = new DefaultRegistry(); private final Id rootId = registry.createId("junit"); @Test public void testUpdates() { MultiDimensionalGauge mg = SpectatorExt.multiDimensionalGauge(rootId, asList("tagA", "tagB"), registry); // Initial state mg.beginUpdate() .set(asList("tagA", "a1", "tagB", "b1"), 1) .set(asList("tagB", "b2", "tagA", "a2"), 2) .commit(); assertGauge(mg, asList("a1", "b1"), 1); assertGauge(mg, asList("a2", "b2"), 2); // Update mg.beginUpdate() .set(asList("tagB", "b1", "tagA", "a1"), 3) .set(asList("tagB", "b3", "tagA", "a1"), 4) .commit(); assertGauge(mg, asList("a1", "b1"), 3); assertGauge(mg, asList("a1", "b3"), 4); assertGaugeMissing(mg, asList("a2", "b2")); // Clear mg.remove(); assertThat(mg.gaugesByTagValues).isEmpty(); } @Test public void testRevisionOrder() { MultiDimensionalGauge mg = SpectatorExt.multiDimensionalGauge(rootId, Collections.singletonList("tagA"), registry); MultiDimensionalGauge.Setter setter1 = mg.beginUpdate() .set(asList("tagA", "a1"), 1); mg.beginUpdate() .set(asList("tagA", "a1"), 2) .commit(); setter1.commit(); assertGauge(mg, Collections.singletonList("a1"), 2); } @Test(expected = IllegalArgumentException.class) public void testFailsOnBadTagName() { SpectatorExt.multiDimensionalGauge(rootId, Collections.singletonList("tagA"), registry) .beginUpdate() .set(asList("tagB", "a1"), 1); } @Test(expected = IllegalArgumentException.class) public void testFailsOnBadTagCount() { SpectatorExt.multiDimensionalGauge(rootId, asList("tagA", "tagB"), registry) .beginUpdate() .set(asList("tagA", "a1"), 1) .commit(); } private void assertGauge(MultiDimensionalGauge mg, List<String> tagValues, double expectedValue) { Gauge gauge = mg.gaugesByTagValues.get(tagValues); assertThat(gauge).isNotNull(); assertThat(gauge.value()).isEqualTo(expectedValue); } private void assertGaugeMissing(MultiDimensionalGauge mg, List<String> tagValues) { Gauge gauge = mg.gaugesByTagValues.get(tagValues); assertThat(gauge).isNull(); } }
536
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/spectator/DynamicTagProcessorTest.java
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.spectator; import com.netflix.spectator.api.Counter; import com.netflix.spectator.api.DefaultRegistry; import com.netflix.spectator.api.Id; import com.netflix.spectator.api.Meter; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class DynamicTagProcessorTest { private final DefaultRegistry registry = new DefaultRegistry(); @Test public void testProcessor() { DynamicTagProcessor<Counter> processor = new DynamicTagProcessor<>( registry.createId("myRoot"), new String[]{"tag1", "tag2"}, registry::counter ); processor.withTags("v1_1", "v2_1").ifPresent(Counter::increment); processor.withTags("v1_2", "v2_1").ifPresent(counter -> counter.increment(5)); processor.withTags("v1_2", "v2_2").ifPresent(counter -> counter.increment(10)); // And again the first one processor.withTags("v1_1", "v2_1").ifPresent(Counter::increment); assertThat(getCounter("myRoot", "tag1", "v1_1", "tag2", "v2_1").count()).isEqualTo(2); assertThat(getCounter("myRoot", "tag1", "v1_2", "tag2", "v2_1").count()).isEqualTo(5); assertThat(getCounter("myRoot", "tag1", "v1_2", "tag2", "v2_2").count()).isEqualTo(10); } private Counter getCounter(String name, String... tags) { Id id = registry.createId(name, tags); Meter meter = registry.get(id); assertThat(meter).isNotNull().isInstanceOf(Counter.class); return (Counter) meter; } }
537
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/spectator/ValueRangeCounterTest.java
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.spectator; import com.netflix.spectator.api.DefaultRegistry; import com.netflix.spectator.api.Registry; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class ValueRangeCounterTest { private static final long[] LEVELS = new long[]{1, 10, 50, 100, 200, 500}; private final Registry registry = new DefaultRegistry(); @Test public void testIncrement() { ValueRangeCounter counters = SpectatorExt.newValueRangeCounter(registry.createId("junit"), LEVELS, registry); counters.recordLevel(-1); assertThat(counters.counters.get(1L).count()).isEqualTo(1L); counters.recordLevel(49); assertThat(counters.counters.get(50L).count()).isEqualTo(1L); counters.recordLevel(499); assertThat(counters.counters.get(500L).count()).isEqualTo(1L); counters.recordLevel(500); counters.recordLevel(5000); assertThat(counters.unbounded.count()).isEqualTo(2); } @Test public void testNewSortableFormatter() { testNewSortableFormatter(1, "001", 1, 10, 100); testNewSortableFormatter(9, "009", 1, 10, 100); testNewSortableFormatter(10, "010", 1, 10, 100); testNewSortableFormatter(99, "099", 1, 10, 100); testNewSortableFormatter(100, "100", 1, 10, 100); testNewSortableFormatter(1, "001", 9, 99, 999); testNewSortableFormatter(999, "999", 9, 99, 999); } private void testNewSortableFormatter(long input, String expectedFormat, long... levels) { String actualFormat = ValueRangeCounter.newSortableFormatter(levels).apply(input); assertThat(actualFormat).isEqualTo(expectedFormat); } }
538
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/collections/ConcurrentHashMultimapTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.collections; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Random; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableListMultimap; import com.google.common.collect.ListMultimap; import com.google.common.collect.Multiset; import org.junit.Before; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.catchThrowable; public class ConcurrentHashMultimapTest { private static final int MINIMUM_THREADS = 10; private static final int MAXIMUM_THREADS = 20; private static final int MAX_KEYS_PER_THREAD = 1024; private static final int MAX_ENTRIES_PER_KEY_PER_THREAD = 8192; private static final int POSSIBLE_RANDOM_IDS = 128; private static final int POSSIBLE_RANDOM_VALUES = 10; private ConcurrentHashMultimap<String, TestEntity> multiMap; @Before public void setUp() throws Exception { multiMap = new ConcurrentHashMultimap<>(TestEntity.idExtractor, TestEntity.lastWins); } @Test public void customizableConflictResolution() throws Exception { final ConcurrentHashMultimap.ConflictResolver<TestEntity> onlyReplaceV1 = (old, replacement) -> old.value.contains("v1"); ConcurrentHashMultimap<String, TestEntity> multiMapThatOnlyReplacesV1 = new ConcurrentHashMultimap<>(TestEntity.idExtractor, onlyReplaceV1); multiMapThatOnlyReplacesV1.put("first", new TestEntity("1", "v1")); assertThat(multiMapThatOnlyReplacesV1.put("first", new TestEntity("1", "v2"))).isTrue(); assertThat(multiMapThatOnlyReplacesV1.put("first", new TestEntity("1", "v1"))).isFalse(); } @Test public void asMap() throws Exception { multiMap.put("firstBucket", new TestEntity("1", "v1")); multiMap.put("secondBucket", new TestEntity("2", "v2")); multiMap.put("secondBucket", new TestEntity("3", "v3")); final Map<String, Collection<TestEntity>> map = multiMap.asMap(); assertThat(map).containsOnlyKeys("firstBucket", "secondBucket"); assertThat(map.get("firstBucket")).hasSize(1) .contains(new TestEntity("1", "v1")); assertThat(map.get("secondBucket")).hasSize(2).containsExactly( new TestEntity("2", "v2"), new TestEntity("3", "v3") ); } @Test public void putAndGetReturnsImmutable() throws Exception { multiMap.put("first", new TestEntity("1", "v1")); multiMap.put("first", new TestEntity("2", "v2")); assertThat(multiMap.isEmpty()).isFalse(); assertThat(multiMap.get("first")).hasSize(2).containsExactly( new TestEntity("1", "v1"), new TestEntity("2", "v2") ); Throwable thrown = catchThrowable(() -> multiMap.get("first").add(new TestEntity("3", "v3"))); assertThat(thrown).isInstanceOf(UnsupportedOperationException.class); } @Test public void getNullKey() throws Exception { multiMap.put("first", new TestEntity("1", "v1")); assertThat(multiMap.get(null)).isEmpty(); } @Test public void remove() throws Exception { multiMap.put("first", new TestEntity("1", "v1")); multiMap.put("first", new TestEntity("2", "v2")); assertThat(multiMap.remove(null, null)).isFalse(); assertThat(multiMap.remove("first", null)).isFalse(); assertThat(multiMap.remove(null, new TestEntity("foo", "bar"))).isFalse(); assertThat(multiMap.remove("first", new TestEntity("foo", "bar"))).isFalse(); assertThat(multiMap.remove("first", new TestEntity("v1", "bar"))).isFalse(); assertThat(multiMap.get("first")).hasSize(2); assertThat(multiMap.remove("first", new TestEntity("1", "v1"))).isTrue(); assertThat(multiMap.get("first")).hasSize(1) .doesNotContain(new TestEntity("1", "v1")); } @Test public void removeIf() throws Exception { multiMap.put("first", new TestEntity("1", "v1")); multiMap.put("first", new TestEntity("2", "v2")); assertThat(multiMap.removeIf( "first", new TestEntity("1", "foo"), existing -> "foo".equals(existing.value)) ).isFalse(); assertThat(multiMap.get("first")).hasSize(2); assertThat(multiMap.removeIf( "first", new TestEntity("1", "foo"), existing -> "v1".equals(existing.value)) ).isTrue(); assertThat(multiMap.get("first")).hasSize(1) .doesNotContain(new TestEntity("1", "v1")); } @Test public void removeClearsEmptyKeys() throws Exception { multiMap.put("first", new TestEntity("1", "v1")); multiMap.put("first", new TestEntity("2", "v2")); assertThat(multiMap.remove("first", new TestEntity("1", "v1"))).isTrue(); assertThat(multiMap.get("first")).hasSize(1); assertThat(multiMap.remove("first", new TestEntity("2", "v2"))).isTrue(); assertThat(multiMap.asMap()).doesNotContainKey("first"); assertThat(multiMap.get("first")).isNull(); } @Test public void putAllMultiMap() throws Exception { multiMap.putAll(ImmutableListMultimap.of( "first", new TestEntity("1", "v1"), "second", new TestEntity("2", "v2"), "second", new TestEntity("3", "v3") )); assertThat(multiMap.isEmpty()).isFalse(); assertThat(multiMap.get("first")).hasSize(1).containsExactly(new TestEntity("1", "v1")); assertThat(multiMap.get("second")).hasSize(2).containsExactly( new TestEntity("2", "v2"), new TestEntity("3", "v3") ); } @Test public void putAllKey() throws Exception { multiMap.putAll("first", ImmutableList.of( new TestEntity("1", "v1"), new TestEntity("2", "v2") )); assertThat(multiMap.isEmpty()).isFalse(); assertThat(multiMap.get("first")).hasSize(2).containsExactly( new TestEntity("1", "v1"), new TestEntity("2", "v2") ); } @Test public void replaceValuesIsNotSupported() throws Exception { final List<TestEntity> values = ImmutableList.of(new TestEntity("1", "v1")); multiMap.putAll("first", values); multiMap.replaceValues("first", ImmutableList.of(new TestEntity("1", "v2"))); assertThat(multiMap.get("first")).hasSize(1) .containsExactly(new TestEntity("1", "v2")); } @Test public void removeAll() throws Exception { multiMap.putAll("first", ImmutableList.of( new TestEntity("1", "v1"), new TestEntity("2", "v2") )); assertThat(multiMap.containsKey("first")).isTrue(); assertThat(multiMap.removeAll("first")).hasSize(2).containsExactly( new TestEntity("1", "v1"), new TestEntity("2", "v2") ); assertThat(multiMap.containsKey("first")).isFalse(); } @Test public void clear() throws Exception { multiMap.putAll(ImmutableListMultimap.of( "first", new TestEntity("1", "v1"), "second", new TestEntity("2", "v2"), "second", new TestEntity("3", "v3") )); assertThat(multiMap.asMap()).isNotEmpty(); multiMap.clear(); assertThat(multiMap.asMap()).isEmpty(); } @Test public void keySet() throws Exception { multiMap.putAll(ImmutableListMultimap.of( "first", new TestEntity("1", "v1"), "second", new TestEntity("2", "v2"), "second", new TestEntity("3", "v3") )); assertThat(multiMap.keySet()).containsExactly("first", "second"); } @Test public void keys() throws Exception { multiMap.putAll(ImmutableListMultimap.of( "first", new TestEntity("1", "v1"), "second", new TestEntity("2", "v2"), "second", new TestEntity("3", "v3") )); final Multiset<String> keys = multiMap.keys(); assertThat(keys).hasSize(3); assertThat(keys.elementSet()).hasSize(2); assertThat(keys.count("first")).isEqualTo(1); assertThat(keys.count("second")).isEqualTo(2); } @Test public void values() throws Exception { multiMap.putAll(ImmutableListMultimap.of( "first", new TestEntity("1", "v1"), "second", new TestEntity("2", "v2"), "second", new TestEntity("3", "v3") )); final Collection<TestEntity> values = multiMap.values(); assertThat(values).hasSize(3); assertThat(values).containsExactly( new TestEntity("1", "v1"), new TestEntity("2", "v2"), new TestEntity("3", "v3") ); } @Test public void entries() throws Exception { multiMap.putAll(ImmutableListMultimap.of( "first", new TestEntity("1", "v1"), "second", new TestEntity("2", "v2"), "second", new TestEntity("3", "v3") )); final Collection<Map.Entry<String, TestEntity>> entries = multiMap.entries(); assertThat(entries).hasSize(3); assertThat(entries).containsExactly( SimpleEntry.of("first", new TestEntity("1", "v1")), SimpleEntry.of("second", new TestEntity("2", "v2")), SimpleEntry.of("second", new TestEntity("3", "v3")) ); } @Test public void size() throws Exception { multiMap.putAll(ImmutableListMultimap.of( "first", new TestEntity("1", "v1"), "second", new TestEntity("2", "v2"), "second", new TestEntity("3", "v3") )); assertThat(multiMap.size()).isEqualTo(3); } @Test public void containsValue() throws Exception { multiMap.putAll(ImmutableListMultimap.of( "first", new TestEntity("1", "v1"), "second", new TestEntity("2", "v2"), "second", new TestEntity("3", "v3") )); assertThat(multiMap.containsValue(new TestEntity("1", "v1"))).isTrue(); assertThat(multiMap.containsValue(new TestEntity("2", "v2"))).isTrue(); assertThat(multiMap.containsValue(new TestEntity("3", "v3"))).isTrue(); } @Test public void containsEntry() throws Exception { multiMap.putAll(ImmutableListMultimap.of( "first", new TestEntity("1", "v1"), "second", new TestEntity("2", "v2"), "second", new TestEntity("3", "v3") )); assertThat(multiMap.containsEntry("first", new TestEntity("1", "v1"))).isTrue(); assertThat(multiMap.containsEntry("first", new TestEntity("2", "v2"))).isFalse(); assertThat(multiMap.containsEntry("second", new TestEntity("2", "v2"))).isTrue(); assertThat(multiMap.containsEntry("second", new TestEntity("3", "v3"))).isTrue(); } @Test public void concurrentPutAllMultimap() throws Exception { ListMultimap<String, TestEntity> allGenerated = randomEntriesInMultipleThreads(itemsPerThread -> { multiMap.putAll(itemsPerThread); }); assertThat(multiMap.keySet()).hasSize(allGenerated.keySet().size()); allGenerated.entries().forEach( entry -> assertThat(multiMap.containsEntry(entry.getKey(), entry.getValue())).isTrue() ); } @Test public void concurrentPutAllPerKey() throws Exception { ListMultimap<String, TestEntity> allGenerated = randomEntriesInMultipleThreads(itemsPerThread -> { itemsPerThread.asMap().forEach( (key, values) -> multiMap.putAll(key, values) ); }); assertThat(multiMap.keySet()).hasSize(allGenerated.keySet().size()); allGenerated.entries().forEach( entry -> assertThat(multiMap.containsEntry(entry.getKey(), entry.getValue())).isTrue() ); } @Test public void concurrentPut() throws Exception { ListMultimap<String, TestEntity> allGenerated = randomEntriesInMultipleThreads(itemsPerThread -> { itemsPerThread.entries().forEach( entry -> multiMap.put(entry.getKey(), entry.getValue()) ); }); assertThat(multiMap.keySet()).hasSize(allGenerated.keySet().size()); allGenerated.entries().forEach( entry -> assertThat(multiMap.containsEntry(entry.getKey(), entry.getValue())).isTrue() ); } private ListMultimap<String, TestEntity> randomEntriesInMultipleThreads(Consumer<ListMultimap<String, TestEntity>> handler) throws InterruptedException { Random r = new Random(); final int numberOfThreads = r.nextInt(MAXIMUM_THREADS - MINIMUM_THREADS) + MINIMUM_THREADS; final Random random = new Random(); List<ListMultimap<String, TestEntity>> perThread = new ArrayList<>(numberOfThreads); for (int i = 0; i < numberOfThreads; i++) { final ImmutableListMultimap.Builder<String, TestEntity> builder = ImmutableListMultimap.builder(); for (int key = 0; key < random.nextInt(MAX_KEYS_PER_THREAD); key++) { for (int entry = 0; entry < random.nextInt(MAX_ENTRIES_PER_KEY_PER_THREAD); entry++) { String id = "" + random.nextInt(POSSIBLE_RANDOM_IDS); String value = "" + random.nextInt(POSSIBLE_RANDOM_VALUES); builder.put("" + key, new TestEntity(id, value)); } } perThread.add(builder.build()); } final ArrayListMultimap<String, TestEntity> flattened = ArrayListMultimap.create(); perThread.forEach(flattened::putAll); CountDownLatch latch = new CountDownLatch(numberOfThreads); // add from different threads in parallel for (int i = 0; i < numberOfThreads; i++) { final ListMultimap<String, TestEntity> currentThreadItems = perThread.get(i); new Thread(() -> { handler.accept(currentThreadItems); latch.countDown(); }).start(); } assertThat(latch.await(15, TimeUnit.SECONDS)).isTrue(); return flattened; } private static class TestEntity { static final ConcurrentHashMultimap.ValueIdentityExtractor<TestEntity> idExtractor = e -> e.id; static final ConcurrentHashMultimap.ConflictResolver<TestEntity> lastWins = (original, replacement) -> true; final String id; final String value; TestEntity(String id, String value) { this.id = id; this.value = value; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } TestEntity that = (TestEntity) o; if (!id.equals(that.id)) { return false; } return value.equals(that.value); } } }
539
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/collections
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/collections/index/DefaultIndexTest.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.collections.index; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class DefaultIndexTest { private static final IndexSpec<String, String, SampleNestedItem, String> SPEC = IndexSpec.<String, String, SampleNestedItem, String>newBuilder() .withIndexKeysExtractor(item -> new HashSet<>(item.getChildren().keySet())) .withPrimaryKeyExtractor(SampleNestedItem::getRootId) .withIndexKeyComparator(String::compareTo) .withPrimaryKeyComparator(String::compareTo) .withTransformer((key, value) -> value.getChildren().get(key)) .build(); private static final DefaultIndex<String, String, SampleNestedItem, String> EMPTY_INDEX = DefaultIndex.newEmpty(SPEC); @Test public void testAdd() { // Initial DefaultIndex<String, String, SampleNestedItem, String> index = EMPTY_INDEX.add(Arrays.asList( SampleNestedItem.newItem("r1", "r1c1", "v1", "r1c2", "v2"), SampleNestedItem.newItem("r2", "r2c1", "v1", "r2c2", "v2") )); assertThat(index.get()).hasSize(4); assertThat(index.get()).containsKeys("r1c1", "r1c2", "r2c1", "r2c2"); // Change existing child. index = index.add(SampleNestedItem.newItemList("r1", "r1c1", "v1b", "r1c2", "v2")); assertThat(index.get()).hasSize(4); assertThat(index.get().get("r1c1")).isEqualTo("v1b"); assertThat(index.get().get("r1c2")).isEqualTo("v2"); // Update by removing one of the existing children. index = index.add(SampleNestedItem.newItemList("r1", "r1c1", "v1b")); assertThat(index.get()).hasSize(3); assertThat(index.get().get("r1c1")).isEqualTo("v1b"); assertThat(index.get().get("r1c2")).isNull(); // Update by adding empty children set index = index.add(SampleNestedItem.newItemList("r1")); assertThat(index.get()).hasSize(2); // Add empty index = index.add(SampleNestedItem.newItemList("r3")); assertThat(index.get()).hasSize(2); // Add to empty index = index.add(SampleNestedItem.newItemList("r3", "r3v1", "v1")); assertThat(index.get()).hasSize(3); assertThat(index.get()).containsEntry("r3v1", "v1"); } @Test public void testRemove() { // Initial DefaultIndex<String, String, SampleNestedItem, String> index = EMPTY_INDEX.add(Arrays.asList( SampleNestedItem.newItem("r1", "r1c1", "v1", "r1c2", "v2"), SampleNestedItem.newItem("r2", "r2c1", "v1", "r2c2", "v2") )); // Remove index = index.remove(Collections.singleton("r1")); assertThat(index.get()).hasSize(2); assertThat(index.get()).containsKeys("r2c1", "r2c2"); } }
540
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/collections
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/collections/index/DefaultGroupTest.java
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.collections.index; import java.util.Collections; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class DefaultGroupTest { private static final IndexSpec<Character, String, SampleItem, String> SPEC = IndexSpec.<Character, String, SampleItem, String>newBuilder() .withIndexKeyExtractor(item -> item.getKey().charAt(0)) .withPrimaryKeyExtractor(SampleItem::getKey) .withIndexKeyComparator(Character::compareTo) .withPrimaryKeyComparator(String::compareTo) .withTransformer((key, value) -> value.getValue()) .build(); private static final DefaultGroup<Character, String, SampleItem, String> EMPTY_GROUP = DefaultGroup.newEmpty(SPEC); @Test public void testAdd() { // Initial DefaultGroup<Character, String, SampleItem, String> group = EMPTY_GROUP.add(SampleItem.newItems("a1", "#a1", "a2", "#a2", "b1", "#b1")); assertThat(group.get()).containsKeys('a', 'b'); assertThat(group.get().get('a')).containsEntry("a1", "#a1"); assertThat(group.get().get('a')).containsEntry("a2", "#a2"); assertThat(group.get().get('b')).containsEntry("b1", "#b1"); // Add to existing subset. group = group.add(SampleItem.newItems("b2", "#b2")); assertThat(group.get().get('b')).containsEntry("b1", "#b1"); assertThat(group.get().get('b')).containsEntry("b2", "#b2"); // Add new subset group = group.add(SampleItem.newItems("c1", "#c1")); assertThat(group.get().get('c')).containsEntry("c1", "#c1"); } @Test public void testRemove() { DefaultGroup<Character, String, SampleItem, String> group = EMPTY_GROUP.add(SampleItem.newItems("a1", "#a1", "a2", "#a2", "b1", "#b1")); // Non empty result subset group = group.remove(Collections.singleton("a1")); assertThat(group.get().get('a')).containsOnlyKeys("a2"); // Remove non-existent key DefaultGroup<Character, String, SampleItem, String> noChange = group.remove(Collections.singleton("a1")); assertThat(group == noChange).isTrue(); // Empty subset group = group.remove(Collections.singleton("a2")); assertThat(group.get().get('a')).isNull(); } }
541
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/collections
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/collections/index/DefaultOrderTest.java
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.collections.index; import java.util.Collections; import org.junit.Test; import static com.netflix.titus.common.util.collections.index.SampleItem.newItems; import static org.assertj.core.api.Assertions.assertThat; public class DefaultOrderTest { private static final IndexSpec<Character, String, SampleItem, String> SPEC = IndexSpec.<Character, String, SampleItem, String>newBuilder() .withIndexKeyExtractor(item -> item.getKey().charAt(0)) .withPrimaryKeyExtractor(SampleItem::getKey) .withIndexKeyComparator(Character::compareTo) .withPrimaryKeyComparator(String::compareTo) .withTransformer((key, value) -> value.getValue()) .build(); private static final DefaultOrder<Character, String, SampleItem, String> EMPTY_INDEX = DefaultOrder.newEmpty(SPEC); @Test public void testAdd() { // Initial DefaultOrder<Character, String, SampleItem, String> index = EMPTY_INDEX.add(newItems("a1", "#a1", "a2", "#a2", "b1", "#b1")); assertThat(index.orderedList()).contains("#a1", "#a2", "#b1"); // Add index = index.add(newItems("b2", "#b2", "a3", "#a3")); assertThat(index.orderedList()).contains("#a1", "#a2", "#a3", "#b1", "#b2"); } @Test public void testRemove() { DefaultOrder<Character, String, SampleItem, String> index = EMPTY_INDEX.add( newItems("a1", "#a1", "a2", "#a2", "b1", "#b1", "b2", "#b2") ); assertThat(index.orderedList()).containsExactly("#a1", "#a2", "#b1", "#b2"); index = index.remove(Collections.singleton("a1")); assertThat(index.orderedList()).containsExactly("#a2", "#b1", "#b2"); index = index.remove(Collections.singleton("a2")); assertThat(index.orderedList()).containsExactly("#b1", "#b2"); index = index.remove(Collections.singleton("b2")); assertThat(index.orderedList()).containsExactly("#b1"); index = index.remove(Collections.singleton("b1")); assertThat(index.orderedList()).isEmpty(); } }
542
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/collections
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/collections/index/SamplePerfItem.java
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.collections.index; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Function; class SamplePerfItem { private static final AtomicLong id = new AtomicLong(); private final String primaryKey; private final String slot; private final long version; SamplePerfItem(String primaryKey, String slot, long version) { this.primaryKey = primaryKey; this.slot = slot; this.version = version; } public String getPrimaryKey() { return primaryKey; } public String getSlot() { return slot; } public long getVersion() { return version; } SamplePerfItem nextVersion() { return new SamplePerfItem(primaryKey, slot, version + 1); } public static SamplePerfItem oneRandom() { String primaryKey = "id#" + id.getAndIncrement(); String slot = "slot#" + (int) (Math.random() * 100); return new SamplePerfItem(primaryKey, slot, 0); } public static List<SamplePerfItem> someRandom(int count) { List<SamplePerfItem> result = new ArrayList<>(); for (int i = 0; i < count; i++) { result.add(oneRandom()); } return result; } static Function<SamplePerfItem, SlotKey> slotKeyExtractor() { return SlotKey::new; } static class SlotKey implements Comparable<SlotKey> { private final String slot; private final String primaryKey; SlotKey(SamplePerfItem sample) { this.slot = sample.slot; this.primaryKey = sample.primaryKey; } public String getSlot() { return slot; } public String getPrimaryKey() { return primaryKey; } @Override public int compareTo(SlotKey other) { int cmp = slot.compareTo(other.slot); if (cmp != 0) { return cmp; } return primaryKey.compareTo(other.primaryKey); } } }
543
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/collections
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/collections/index/IndexSetMetricsTest.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.collections.index; import java.io.Closeable; import com.netflix.spectator.api.DefaultRegistry; import com.netflix.spectator.api.Registry; import com.netflix.titus.common.util.ExceptionExt; import org.junit.Test; public class IndexSetMetricsTest { private final Registry registry = new DefaultRegistry(); private static final IndexSpec<Character, String, SampleItem, String> SPEC = IndexSpec.<Character, String, SampleItem, String>newBuilder() .withIndexKeyExtractor(item -> item.getKey().charAt(0)) .withPrimaryKeyExtractor(SampleItem::getKey) .withIndexKeyComparator(Character::compareTo) .withPrimaryKeyComparator(String::compareTo) .withTransformer((key, value) -> value.getValue()) .build(); @Test public void testMetrics() { IndexSetHolder<String, SampleItem> indexSetHolder = new IndexSetHolderBasic<>( Indexes.<String, SampleItem>newBuilder() .withGroup("testGroup", SPEC) .withOrder("testIndex", SPEC) .build() ); Closeable closeable = Indexes.monitor(registry.createId("test"), indexSetHolder, registry); ExceptionExt.silent(closeable::close); } }
544
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/collections
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/collections/index/SampleItem.java
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.collections.index; import java.util.ArrayList; import java.util.List; class SampleItem { private final String key; private final String value; public SampleItem(String key, String value) { this.key = key; this.value = value; } public String getKey() { return key; } public String getValue() { return value; } static List<SampleItem> newItems(String... keyValuePairs) { List<SampleItem> result = new ArrayList<>(); for (int i = 0; i < keyValuePairs.length; i += 2) { result.add(new SampleItem(keyValuePairs[i], keyValuePairs[i + 1])); } return result; } }
545
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/collections
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/collections/index/IndexPerf.java
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.collections.index; import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; import com.google.common.base.Stopwatch; import com.netflix.titus.common.util.collections.index.SamplePerfItem.SlotKey; import static org.assertj.core.api.Assertions.assertThat; public class IndexPerf { public static final String BY_PRIMARY_KEY = "byPrimaryKey"; public static final String BY_SLOT = "bySlot"; private static final String GROUP_BY_SLOT = "groupBySlot"; public static void main(String[] args) { IndexSet<String, SamplePerfItem> indexSet = Indexes.<String, SamplePerfItem>newBuilder() .withOrder(BY_PRIMARY_KEY, IndexSpec.<String, String, SamplePerfItem, SamplePerfItem>newBuilder() .withIndexKeyExtractor(SamplePerfItem::getPrimaryKey) .withPrimaryKeyExtractor(SamplePerfItem::getPrimaryKey) .withIndexKeyComparator(String::compareTo) .withPrimaryKeyComparator(String::compareTo) .build() ) .withOrder(BY_SLOT, IndexSpec.<SlotKey, String, SamplePerfItem, SamplePerfItem>newBuilder() .withIndexKeyExtractor(SamplePerfItem.slotKeyExtractor()) .withPrimaryKeyExtractor(SamplePerfItem::getPrimaryKey) .withIndexKeyComparator(SlotKey::compareTo) .withPrimaryKeyComparator(String::compareTo) .build() ) .withGroup(GROUP_BY_SLOT, IndexSpec.<String, String, SamplePerfItem, SamplePerfItem>newBuilder() .withIndexKeyExtractor(SamplePerfItem::getSlot) .withPrimaryKeyExtractor(SamplePerfItem::getPrimaryKey) .withIndexKeyComparator(String::compareTo) .withPrimaryKeyComparator(String::compareTo) .build()) .build(); Stopwatch stopwatch = Stopwatch.createStarted(); for (int i = 0; i < 2000; i++) { indexSet = indexSet.add(SamplePerfItem.someRandom(20)); } printStats("Initialization", indexSet, stopwatch); stopwatch.reset().start(); List<SamplePerfItem> all = indexSet.<SamplePerfItem>getOrder(BY_PRIMARY_KEY).orderedList(); for (SamplePerfItem sampleValue : all) { indexSet = indexSet.add(Collections.singletonList(sampleValue.nextVersion())); } printStats("Update", indexSet, stopwatch); List<SamplePerfItem> all2 = indexSet.<SamplePerfItem>getOrder(BY_PRIMARY_KEY).orderedList(); for (int i = 0; i < all.size(); i++) { SamplePerfItem before = all.get(i); SamplePerfItem after = all2.get(i); assertThat(before.getPrimaryKey()).isEqualTo(after.getPrimaryKey()); assertThat(before.getVersion()).isLessThan(after.getVersion()); } } private static void printStats(String header, IndexSet<String, SamplePerfItem> indexSet, Stopwatch stopwatch) { System.out.println(header); System.out.printf("Elapsed : %dms\n", stopwatch.elapsed(TimeUnit.MILLISECONDS)); System.out.println("byPrimaryKey size: " + indexSet.getOrder(BY_PRIMARY_KEY).orderedList().size()); System.out.println("bySlot size : " + indexSet.getOrder(BY_SLOT).orderedList().size()); System.out.println("groupBySlot size : " + indexSet.getGroup(GROUP_BY_SLOT).get().size()); System.out.println(); } }
546
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/collections
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/collections/index/SampleNestedItem.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.collections.index; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; public class SampleNestedItem { private final String rootId; private final Map<String, String> children; public SampleNestedItem(String rootId, Map<String, String> children) { this.rootId = rootId; this.children = children; } public String getRootId() { return rootId; } public Map<String, String> getChildren() { return children; } public static SampleNestedItem newItem(String rootId, String... keyValuePairs) { Map<String, String> children = new HashMap<>(); for (int i = 0; i < keyValuePairs.length; i += 2) { children.put(keyValuePairs[i], keyValuePairs[i + 1]); } return new SampleNestedItem(rootId, children); } public static List<SampleNestedItem> newItemList(String rootId, String... keyValuePairs) { return Collections.singletonList(newItem(rootId, keyValuePairs)); } }
547
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/event/EventPropagationUtilTest.java
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.event; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class EventPropagationUtilTest { private static final List<String> CLIENT_LABELS = Arrays.asList("tjcInternal", "gatewayClient", "gatewayInternal", "federationClient", "federationInternal", "client"); private static final List<String> FEDERATION_LABELS = Arrays.asList("tjcInternal", "gatewayClient", "gatewayInternal", "federationClient", "federationInternal"); @Test public void testTitusPropagationTrackingInClient() { Map<String, String> attributes = Collections.singletonMap("keyA", "valueA"); // TJC -> Gateway Map<String, String> stage1 = EventPropagationUtil.copyAndAddNextStage("s1", attributes, 100, 150); assertThat(stage1).containsEntry(EventPropagationUtil.EVENT_ATTRIBUTE_PROPAGATION_STAGES, "s1(50ms):before=100,after=150"); // Gateway -> Federation Map<String, String> stage2 = EventPropagationUtil.copyAndAddNextStage("s2", stage1, 300, 400); assertThat(stage2).containsEntry(EventPropagationUtil.EVENT_ATTRIBUTE_PROPAGATION_STAGES, "s1(50ms):before=100,after=150;s2(100ms):before=300,after=400"); // Federation -> client Map<String, String> stage3 = EventPropagationUtil.copyAndAddNextStage("s3", stage2, 1000, 1200); assertThat(stage3).containsEntry(EventPropagationUtil.EVENT_ATTRIBUTE_PROPAGATION_STAGES, "s1(50ms):before=100,after=150;s2(100ms):before=300,after=400;s3(200ms):before=1000,after=1200"); // Result EventPropagationTrace clientTrace = EventPropagationUtil.parseTrace(stage3, false, 10, CLIENT_LABELS).orElse(null); assertThat(clientTrace).isNotNull(); assertThat(clientTrace.getStages()).containsEntry("tjcInternal", 90L); assertThat(clientTrace.getStages()).containsEntry("gatewayClient", 50L); assertThat(clientTrace.getStages()).containsEntry("gatewayInternal", 150L); assertThat(clientTrace.getStages()).containsEntry("federationClient", 100L); assertThat(clientTrace.getStages()).containsEntry("federationInternal", 600L); assertThat(clientTrace.getStages()).containsEntry("client", 200L); } @Test public void testTitusPropagationTrackingInFederation() { Map<String, String> attributes = Collections.singletonMap( EventPropagationUtil.EVENT_ATTRIBUTE_PROPAGATION_STAGES, "before=100,after=150;before=300,after=400;before=1000,after=1000" ); // Federation trace does not include federation -> client latency, but includes federation internal processing EventPropagationTrace federationTrace = EventPropagationUtil.parseTrace(attributes, false, 10, FEDERATION_LABELS).orElse(null); assertThat(federationTrace).isNotNull(); assertThat(federationTrace.getStages()).containsEntry("federationInternal", 600L); assertThat(federationTrace.getStages()).doesNotContainKey("client"); } @Test public void testTitusPropagationTrackingTooLong () { Map<String, String> attributes = Collections.singletonMap("keyA", "valueA"); int ts = 0; for (int i = 0; i < 100; i++) { ts = ts + 100; attributes = EventPropagationUtil.copyAndAddNextStage("s" + i, attributes, ts, ts + 200); assertThat(attributes).containsKey(EventPropagationUtil.EVENT_ATTRIBUTE_PROPAGATION_STAGES); } EventPropagationTrace clientTrace = EventPropagationUtil.parseTrace(attributes, false, ts, CLIENT_LABELS).orElse(null); assertThat(clientTrace).isNotNull(); assertThat(attributes).containsKey(EventPropagationUtil.EVENT_ATTRIBUTE_PROPAGATION_STAGES); String traceStr = attributes.get(EventPropagationUtil.EVENT_ATTRIBUTE_PROPAGATION_STAGES); assertThat(traceStr.length()).isLessThan(EventPropagationUtil.MAX_LENGTH_EVENT_PROPAGATION_STAGE); } }
548
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/rx/ReactorReEmitterOperatorTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx; import java.time.Duration; import org.junit.Test; import reactor.core.publisher.Flux; import reactor.core.scheduler.Schedulers; import reactor.test.StepVerifier; import static org.assertj.core.api.Assertions.assertThat; public class ReactorReEmitterOperatorTest { private static final Duration EMIT_INTERVAL = Duration.ofMillis(1_000); private boolean cancelled; @Test public void testReEmits() { StepVerifier .withVirtualTime(() -> newReEmitter(EMIT_INTERVAL.multipliedBy(5), EMIT_INTERVAL.multipliedBy(2))) .expectSubscription() // Until first item is emitted, there is nothing to re-emit. .expectNoEvent(emitSteps(5)) // First emit .expectNext("0") .expectNoEvent(EMIT_INTERVAL) .expectNext(toReEmitted("0")) // Second emit .expectNoEvent(EMIT_INTERVAL) .expectNext("1") .expectNoEvent(EMIT_INTERVAL) .expectNext(toReEmitted("1")) .thenCancel() .verify(); assertThat(cancelled).isTrue(); } @Test public void testNoReEmits() { Duration sourceInterval = EMIT_INTERVAL.dividedBy(2); StepVerifier .withVirtualTime(() -> newReEmitter(Duration.ofSeconds(0), sourceInterval)) .expectNext("0") .expectNoEvent(sourceInterval) .expectNext("1") .expectNoEvent(sourceInterval) .expectNext("2") .thenCancel() .verify(); } private Duration emitSteps(int steps) { return EMIT_INTERVAL.multipliedBy(steps); } private Flux<String> newReEmitter(Duration delay, Duration interval) { Flux<String> source = Flux.interval(delay, interval) .map(Object::toString) .doOnCancel(() -> this.cancelled = true); return source.transformDeferred(ReactorExt.reEmitter(this::toReEmitted, EMIT_INTERVAL, Schedulers.parallel())); } private String toReEmitted(String tick) { return "Re-emitted#" + tick; } }
549
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/rx/ValueGeneratorTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Supplier; import com.jayway.awaitility.Awaitility; import org.junit.Test; import rx.Producer; import rx.Subscriber; import rx.Subscription; import static org.assertj.core.api.Assertions.assertThat; public class ValueGeneratorTest { @Test public void testSimpleValueGeneration() throws Exception { final int limit = 100; AtomicInteger valueSource = new AtomicInteger(); AtomicInteger emitCounter = new AtomicInteger(); CountDownLatch latch = new CountDownLatch(1); Subscription subscription = ObservableExt.generatorFrom(valueSource::getAndIncrement).subscribe(new Subscriber<Integer>() { private Producer producer; @Override public void setProducer(Producer p) { this.producer = p; p.request(1); } @Override public void onCompleted() { latch.countDown(); } @Override public void onError(Throwable e) { latch.countDown(); e.printStackTrace(); } @Override public void onNext(Integer integer) { if (emitCounter.incrementAndGet() < limit) { producer.request(1); } else { unsubscribe(); latch.countDown(); } } }); latch.await(); assertThat(emitCounter.get()).isEqualTo(limit); Awaitility.await().timeout(5, TimeUnit.SECONDS).until(subscription::isUnsubscribed); } @Test public void testFailureInValueProviderIsPropagatedToSubscriber() throws Exception { Supplier<Integer> failingSupplier = () -> { throw new RuntimeException("simulated error"); }; AtomicReference<Throwable> errorRef = new AtomicReference<>(); CountDownLatch latch = new CountDownLatch(1); Subscription subscription = ObservableExt.generatorFrom(failingSupplier).subscribe(new Subscriber<Integer>() { @Override public void setProducer(Producer p) { p.request(1); } @Override public void onCompleted() { latch.countDown(); } @Override public void onError(Throwable e) { errorRef.set(e); latch.countDown(); } @Override public void onNext(Integer integer) { } }); latch.await(); Awaitility.await().timeout(5, TimeUnit.SECONDS).until(subscription::isUnsubscribed); assertThat(errorRef.get()).hasMessageContaining("simulated error"); } }
550
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/rx/SubscriptionTimeoutTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.function.Supplier; import org.junit.Before; import org.junit.Test; import rx.observers.AssertableSubscriber; import rx.schedulers.Schedulers; import rx.schedulers.TestScheduler; import rx.subjects.PublishSubject; import rx.subjects.SerializedSubject; public class SubscriptionTimeoutTest { private static final Supplier<Long> TEST_TIMEOUT_MS = () -> 10_000L; private SerializedSubject<String, String> source; private TestScheduler testScheduler; private AssertableSubscriber<String> subscriber; @Before public void setUp() throws Exception { this.source = PublishSubject.<String>create().toSerialized(); this.testScheduler = Schedulers.test(); this.subscriber = source .lift(new SubscriptionTimeout<>(TEST_TIMEOUT_MS, TimeUnit.MILLISECONDS, testScheduler)) .test(); } @Test public void doesNotErrorBeforeTimeout() { testScheduler.triggerActions(); subscriber.assertNoValues() .assertNoErrors() .assertNoTerminalEvent(); testScheduler.advanceTimeBy(TEST_TIMEOUT_MS.get() - 1, TimeUnit.MILLISECONDS); subscriber.assertNoValues() .assertNoErrors() .assertNoTerminalEvent(); source.onNext("one"); subscriber.assertNoErrors() .assertValuesAndClear("one") .assertNoTerminalEvent(); source.onCompleted(); subscriber.assertNoValues() .assertNoErrors() .assertCompleted(); source.onNext("invalid"); subscriber.assertNoValues() .assertNoErrors() .assertCompleted(); testScheduler.advanceTimeBy(1, TimeUnit.MILLISECONDS); subscriber.assertNoValues() .assertNoErrors() .assertCompleted(); testScheduler.advanceTimeBy(TEST_TIMEOUT_MS.get(), TimeUnit.MILLISECONDS); subscriber.assertNoValues() .assertNoErrors() .assertCompleted(); } @Test public void timeoutEmitsOnError() { testScheduler.triggerActions(); subscriber.assertNoValues() .assertNoErrors() .assertNoTerminalEvent(); // emit some items for some time before the timeout (TEST_TIMEOUT_MS - 1) final int items = 10; for (int i = 0; i <= items - 1; i++) { source.onNext("" + i); testScheduler.advanceTimeBy((TEST_TIMEOUT_MS.get() - 1) / items, TimeUnit.MILLISECONDS); subscriber.assertNoErrors() .assertValuesAndClear("" + i) .assertNoTerminalEvent(); } testScheduler.advanceTimeBy(TEST_TIMEOUT_MS.get() / items, TimeUnit.MILLISECONDS); subscriber.assertNoValues() .assertError(TimeoutException.class); source.onNext("invalid"); testScheduler.triggerActions(); subscriber.assertNoValues(); testScheduler.advanceTimeBy(TEST_TIMEOUT_MS.get() / items, TimeUnit.MILLISECONDS); subscriber.assertNoValues(); } }
551
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/rx/ComputationTaskInvokerTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import com.netflix.titus.testkit.rx.ExtTestSubscriber; import org.junit.Test; import rx.Observable; import rx.schedulers.Schedulers; import rx.schedulers.TestScheduler; import static org.assertj.core.api.Assertions.assertThat; public class ComputationTaskInvokerTest { private static final long TASK_DELAY_MS = 30; private final TestScheduler testScheduler = Schedulers.test(); private final AtomicInteger invocationCounter = new AtomicInteger(); private final ComputationTaskInvoker<String> invoker = new ComputationTaskInvoker<>( Observable.timer(TASK_DELAY_MS, TimeUnit.MILLISECONDS, testScheduler).map(tick -> "Done round " + invocationCounter.getAndIncrement()), testScheduler ); @Test public void testNonContentedComputation() throws Exception { ExtTestSubscriber<String> testSubscriber = new ExtTestSubscriber<>(); invoker.recompute().subscribe(testSubscriber); testScheduler.advanceTimeBy(TASK_DELAY_MS, TimeUnit.MILLISECONDS); assertThat(testSubscriber.takeNext()).isEqualTo("Done round 0"); assertThat(testSubscriber.isUnsubscribed()).isTrue(); assertThat(invocationCounter.get()).isEqualTo(1); } @Test public void testContentedComputation() throws Exception { ExtTestSubscriber<String> testSubscriber1 = new ExtTestSubscriber<>(); ExtTestSubscriber<String> testSubscriber2 = new ExtTestSubscriber<>(); ExtTestSubscriber<String> testSubscriber3 = new ExtTestSubscriber<>(); invoker.recompute().subscribe(testSubscriber1); // Advance time to start computation testScheduler.advanceTimeBy(1, TimeUnit.MILLISECONDS); // Now subscriber again. The new subscriptions should wait for their turn. invoker.recompute().subscribe(testSubscriber2); invoker.recompute().subscribe(testSubscriber3); testScheduler.advanceTimeBy(TASK_DELAY_MS - 1, TimeUnit.MILLISECONDS); assertThat(testSubscriber1.takeNext()).isEqualTo("Done round 0"); assertThat(testSubscriber1.isUnsubscribed()).isTrue(); assertThat(testSubscriber2.takeNext()).isNull(); assertThat(testSubscriber3.takeNext()).isNull(); assertThat(invocationCounter.get()).isEqualTo(1); // Now trigger next computation testScheduler.advanceTimeBy(TASK_DELAY_MS, TimeUnit.MILLISECONDS); assertThat(testSubscriber2.takeNext()).isEqualTo("Done round 1"); assertThat(testSubscriber3.takeNext()).isEqualTo("Done round 1"); assertThat(invocationCounter.get()).isEqualTo(2); } @Test public void testFailingComputations() throws Exception { AtomicBoolean flag = new AtomicBoolean(); ComputationTaskInvoker<String> slowInvoker = new ComputationTaskInvoker<>( Observable.create(subscriber -> { if (flag.getAndSet(true)) { subscriber.onNext("OK!"); subscriber.onCompleted(); } else { Observable.<String>timer(1, TimeUnit.SECONDS, testScheduler) .flatMap(tick -> Observable.<String>error(new RuntimeException("simulated computation error"))) .subscribe(subscriber); } }), testScheduler ); ExtTestSubscriber<String> failingSubscriber = new ExtTestSubscriber<>(); slowInvoker.recompute().subscribe(failingSubscriber); testScheduler.triggerActions(); ExtTestSubscriber<String> okSubscriber = new ExtTestSubscriber<>(); slowInvoker.recompute().subscribe(okSubscriber); testScheduler.advanceTimeBy(1, TimeUnit.SECONDS); failingSubscriber.assertOnError(); assertThat(okSubscriber.takeNext()).isEqualTo("OK!"); okSubscriber.assertOnCompleted(); } }
552
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/rx/EventEmitterTransformerTest.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx; import java.util.Iterator; import java.util.List; import java.util.Objects; import org.junit.Test; import reactor.core.publisher.DirectProcessor; import reactor.core.publisher.Flux; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; public class EventEmitterTransformerTest { private static final StringEvent SNAPSHOT_END = new StringEvent("SNAPSHOT_END", true); private final DirectProcessor<List<String>> source = DirectProcessor.create(); private final Flux<StringEvent> events = source.transformDeferred(ReactorExt.eventEmitter( string -> string.substring(0, 1), String::equals, string -> new StringEvent(string, true), string -> new StringEvent(string, false), SNAPSHOT_END )); @Test public void testAdd() { Iterator<StringEvent> output = events.toIterable().iterator(); source.onNext(asList("a", "b")); assertThat(output.next()).isEqualTo(new StringEvent("a", true)); assertThat(output.next()).isEqualTo(new StringEvent("b", true)); assertThat(output.next()).isEqualTo(SNAPSHOT_END); source.onNext(asList("a", "b", "c")); assertThat(output.next()).isEqualTo(new StringEvent("c", true)); } @Test public void testRemove() { Iterator<StringEvent> output = events.toIterable().iterator(); source.onNext(asList("a", "b")); assertThat(output.next()).isEqualTo(new StringEvent("a", true)); assertThat(output.next()).isEqualTo(new StringEvent("b", true)); assertThat(output.next()).isEqualTo(SNAPSHOT_END); source.onNext(asList("b", "c")); assertThat(output.next()).isEqualTo(new StringEvent("c", true)); assertThat(output.next()).isEqualTo(new StringEvent("a", false)); } @Test public void testUpdate() { Iterator<StringEvent> output = events.toIterable().iterator(); source.onNext(asList("a", "b")); assertThat(output.next()).isEqualTo(new StringEvent("a", true)); assertThat(output.next()).isEqualTo(new StringEvent("b", true)); assertThat(output.next()).isEqualTo(SNAPSHOT_END); source.onNext(asList("av2")); assertThat(output.next()).isEqualTo(new StringEvent("av2", true)); assertThat(output.next()).isEqualTo(new StringEvent("b", false)); } private static class StringEvent { private final String value; private final boolean added; private StringEvent(String value, boolean added) { this.value = value; this.added = added; } public String getValue() { return value; } public boolean isAdded() { return added; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } StringEvent that = (StringEvent) o; return added == that.added && Objects.equals(value, that.value); } @Override public int hashCode() { return Objects.hash(value, added); } @Override public String toString() { return "StringEvent{" + "value='" + value + '\'' + ", added=" + added + '}'; } } }
553
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/rx/FluxListenerInvocationHandlerTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx; import java.util.Iterator; import java.util.concurrent.atomic.AtomicReference; import org.junit.Test; import reactor.core.Disposable; import static org.assertj.core.api.Assertions.assertThat; public class FluxListenerInvocationHandlerTest { private final EventObservable eventObservable = new EventObservable(); @Test public void testListenerCallback() { Iterator it = ReactorExt.fromListener(EventListener.class, eventObservable::addListener, eventObservable::removeListener).toIterable().iterator(); eventObservable.emit("A"); assertThat(it.hasNext()).isTrue(); assertThat(it.next()).isEqualTo("A"); eventObservable.emit("B"); assertThat(it.hasNext()).isTrue(); assertThat(it.next()).isEqualTo("B"); } @Test public void testCancellation() { Disposable subscription = ReactorExt.fromListener(EventListener.class, eventObservable::addListener, eventObservable::removeListener).subscribe(); assertThat(eventObservable.eventHandler).isNotNull(); subscription.dispose(); assertThat(eventObservable.eventHandler).isNull(); } @Test public void testErrorClosesSubscription() { RuntimeException simulatedError = new RuntimeException("Simulated error"); AtomicReference<Throwable> errorRef = new AtomicReference<>(); Disposable subscription = ReactorExt.fromListener(EventListener.class, eventObservable::addListener, eventObservable::removeListener).subscribe( next -> { throw simulatedError; }, errorRef::set ); eventObservable.emit("A"); assertThat(subscription.isDisposed()).isTrue(); assertThat(errorRef.get()).isEqualTo(simulatedError); } private interface EventListener { void onEvent(String event); } private class EventObservable { private EventListener eventHandler; void addListener(EventListener eventHandler) { this.eventHandler = eventHandler; } void removeListener(EventListener eventHandler) { if (this.eventHandler == eventHandler) { this.eventHandler = null; } } void emit(String value) { if (eventHandler != null) { eventHandler.onEvent(value); } } } }
554
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/rx/ReactorRetryHandlerBuilderTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx; import java.io.IOException; import java.time.Duration; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import javax.naming.ServiceUnavailableException; import org.junit.Test; import reactor.core.publisher.Flux; import reactor.core.scheduler.Schedulers; import reactor.test.StepVerifier; import static com.netflix.titus.common.util.rx.RetryHandlerBuilder.retryHandler; public class ReactorRetryHandlerBuilderTest { private static final long RETRY_DELAY_SEC = 1; @Test public void testRetryOnError() { StepVerifier .withVirtualTime(() -> streamOf("A", new IOException("Error1"), "B", new IOException("Error2"), "C") .retryWhen(newRetryHandlerBuilder().buildRetryExponentialBackoff()) ) // Expect first item .expectNext("A") // Expect second item .expectNoEvent(Duration.ofSeconds(RETRY_DELAY_SEC)) .expectNext("B") // Expect third item .expectNoEvent(Duration.ofSeconds(2 * RETRY_DELAY_SEC)) .expectNext("C") .verifyComplete(); } @Test public void testRetryOnThrowable() { StepVerifier .withVirtualTime(() -> streamOf("A", new ServiceUnavailableException("Retry me"), "B", new IllegalArgumentException("Do not retry me."), "C") .retryWhen(newRetryHandlerBuilder().withRetryOnThrowable(ex -> ex instanceof ServiceUnavailableException).buildRetryExponentialBackoff()) ) .expectNext("A") .expectNoEvent(Duration.ofSeconds(RETRY_DELAY_SEC)) .expectNext("B") .expectErrorMatches(e -> e instanceof IOException && e.getCause() instanceof IllegalArgumentException) .verify(); } @Test public void testMaxRetryDelay() { long expectedDelay = RETRY_DELAY_SEC + 2 * RETRY_DELAY_SEC + 2 * RETRY_DELAY_SEC; StepVerifier .withVirtualTime(() -> streamOf(new IOException("Error1"), new IOException("Error2"), new IOException("Error3"), "A") .retryWhen(newRetryHandlerBuilder() .withMaxDelay(RETRY_DELAY_SEC * 2, TimeUnit.SECONDS) .buildRetryExponentialBackoff() ) ) .expectSubscription() // Expect first item .expectNoEvent(Duration.ofSeconds(expectedDelay)) .expectNext("A") .verifyComplete(); } @Test public void testMaxRetry() { StepVerifier .withVirtualTime(() -> streamOf(new IOException("Error1"), new IOException("Error2"), "A") .retryWhen(newRetryHandlerBuilder() .withRetryCount(1) .buildRetryExponentialBackoff() ) ) .expectSubscription() .expectNoEvent(Duration.ofSeconds(RETRY_DELAY_SEC)) .verifyError(IOException.class); } private Flux<String> streamOf(Object... items) { AtomicInteger pos = new AtomicInteger(); return Flux.create(emitter -> { for (int i = pos.get(); i < items.length; i++) { pos.incrementAndGet(); Object item = items[i]; if (item instanceof Throwable) { emitter.error((Throwable) item); return; } emitter.next((String) item); } emitter.complete(); }); } private RetryHandlerBuilder newRetryHandlerBuilder() { return retryHandler() .withReactorScheduler(Schedulers.parallel()) .withTitle("testObservable") .withRetryCount(3) .withRetryDelay(RETRY_DELAY_SEC, TimeUnit.SECONDS); } }
555
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/rx/FutureOnSubscribeTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import com.netflix.titus.testkit.rx.ExtTestSubscriber; import org.junit.Before; import org.junit.Test; import rx.Subscription; import rx.schedulers.Schedulers; import rx.schedulers.TestScheduler; import static org.assertj.core.api.Assertions.assertThat; public class FutureOnSubscribeTest { private final TestScheduler testScheduler = Schedulers.test(); private final CompletableFuture<String> future = new CompletableFuture<>(); private final ExtTestSubscriber<String> testSubscriber = new ExtTestSubscriber<>(); private Subscription subscription; @Before public void setUp() throws Exception { this.subscription = ObservableExt.toObservable(future, testScheduler).subscribe(testSubscriber); } @Test public void testOk() throws Exception { testScheduler.triggerActions(); assertThat(testSubscriber.isUnsubscribed()).isFalse(); assertThat(testSubscriber.takeNext()).isNull(); future.complete("Hello!"); advance(); assertThat(testSubscriber.isUnsubscribed()).isTrue(); assertThat(subscription.isUnsubscribed()).isTrue(); assertThat(testSubscriber.takeNext()).isEqualTo("Hello!"); } @Test public void testCancelled() throws Exception { future.cancel(true); advance(); assertThat(testSubscriber.isUnsubscribed()).isTrue(); assertThat(testSubscriber.isError()).isTrue(); } @Test public void testException() throws Exception { future.completeExceptionally(new RuntimeException("simulated error")); advance(); assertThat(testSubscriber.isUnsubscribed()).isTrue(); assertThat(testSubscriber.isError()).isTrue(); } @Test public void testUnsubscribe() throws Exception { subscription.unsubscribe(); advance(); assertThat(testSubscriber.isUnsubscribed()).isTrue(); assertThat(testSubscriber.isError()).isFalse(); } private void advance() { testScheduler.advanceTimeBy(FutureOnSubscribe.INITIAL_DELAY_MS, TimeUnit.MILLISECONDS); } }
556
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/rx/RetryHandlerBuilderTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx; import java.io.IOException; import java.time.Duration; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import javax.naming.ServiceUnavailableException; import com.netflix.titus.testkit.rx.ExtTestSubscriber; import io.reactivex.subscribers.TestSubscriber; import org.junit.Test; import reactor.core.publisher.Flux; import reactor.test.scheduler.VirtualTimeScheduler; import reactor.util.retry.Retry; import rx.Observable; import rx.functions.Func1; import rx.schedulers.Schedulers; import rx.schedulers.TestScheduler; import static com.netflix.titus.common.util.rx.RetryHandlerBuilder.retryHandler; import static org.assertj.core.api.Assertions.assertThat; public class RetryHandlerBuilderTest { private static final long RETRY_DELAY_SEC = 1; private final TestScheduler testScheduler = Schedulers.test(); private final ExtTestSubscriber<String> testSubscriber = new ExtTestSubscriber<>(); private final RetryHandlerBuilder builder = retryHandler() .withScheduler(testScheduler) .withTitle("testObservable") .withRetryCount(3) .withRetryDelay(RETRY_DELAY_SEC, TimeUnit.SECONDS); @Test public void testRetryOnError() throws Exception { Func1<Observable<? extends Throwable>, Observable<?>> retryFun = builder.buildExponentialBackoff(); observableOf("A", new IOException("Error1"), "B", new IOException("Error2"), "C") .retryWhen(retryFun, testScheduler) .subscribe(testSubscriber); // Expect first item testScheduler.triggerActions(); assertThat(testSubscriber.getLatestItem()).isEqualTo("A"); // Expect second item testScheduler.advanceTimeBy(RETRY_DELAY_SEC, TimeUnit.SECONDS); assertThat(testSubscriber.getLatestItem()).isEqualTo("B"); // Expect third item testScheduler.advanceTimeBy(2 * RETRY_DELAY_SEC, TimeUnit.SECONDS); assertThat(testSubscriber.getLatestItem()).isEqualTo("C"); assertThat(testSubscriber.isUnsubscribed()); } @Test public void testRetryOnThrowableCondition() throws Exception { Func1<Observable<? extends Throwable>, Observable<?>> retryFun = builder .withRetryOnThrowable(ex -> ex instanceof ServiceUnavailableException) .buildExponentialBackoff(); observableOf("A", new ServiceUnavailableException("Retry me"), "B", new IllegalArgumentException("Do not retry"), "C") .retryWhen(retryFun, testScheduler) .subscribe(testSubscriber); // Expect first item testScheduler.triggerActions(); assertThat(testSubscriber.getLatestItem()).isEqualTo("A"); // Expect second item testScheduler.advanceTimeBy(RETRY_DELAY_SEC, TimeUnit.SECONDS); assertThat(testSubscriber.getLatestItem()).isEqualTo("B"); // Expect third item testScheduler.advanceTimeBy(2 * RETRY_DELAY_SEC, TimeUnit.SECONDS); testSubscriber.assertOnError(IOException.class); assertThat(testSubscriber.isUnsubscribed()); } @Test public void testMaxRetryDelay() throws Exception { Func1<Observable<? extends Throwable>, Observable<?>> retryFun = builder .withMaxDelay(RETRY_DELAY_SEC * 2, TimeUnit.SECONDS) .buildExponentialBackoff(); observableOf(new IOException("Error1"), new IOException("Error2"), new IOException("Error3"), "A") .retryWhen(retryFun, testScheduler) .subscribe(testSubscriber); long expectedDelay = RETRY_DELAY_SEC + 2 * RETRY_DELAY_SEC + 2 * RETRY_DELAY_SEC; // Advance time just before last retry delay testScheduler.advanceTimeBy(expectedDelay - 1, TimeUnit.SECONDS); assertThat(testSubscriber.takeNext()).isNull(); // Now cross it testScheduler.advanceTimeBy(1, TimeUnit.SECONDS); assertThat(testSubscriber.getLatestItem()).isEqualTo("A"); assertThat(testSubscriber.isUnsubscribed()); } @Test public void testMaxRetry() throws Exception { Func1<Observable<? extends Throwable>, Observable<?>> retryFun = builder .withRetryCount(1) .buildExponentialBackoff(); observableOf(new IOException("Error1"), new IOException("Error2"), "A") .retryWhen(retryFun, testScheduler) .subscribe(testSubscriber); testScheduler.advanceTimeBy(RETRY_DELAY_SEC, TimeUnit.SECONDS); assertThat(testSubscriber.getError()).isInstanceOf(IOException.class); } @Test public void testUnlimitedRetries() throws Exception { Func1<Observable<? extends Throwable>, Observable<?>> retryFun = builder .withUnlimitedRetries() .withDelay(RETRY_DELAY_SEC, RETRY_DELAY_SEC * 4, TimeUnit.SECONDS) .buildExponentialBackoff(); final Observable<String> observables = Observable.range(1, 100) .map(i -> new RuntimeException("Error " + i)) .flatMap(this::observableOf); observables.retryWhen(retryFun, testScheduler).subscribe(testSubscriber); testScheduler.advanceTimeBy(RETRY_DELAY_SEC * 10000, TimeUnit.SECONDS); assertThat(testSubscriber.getError()).isNull(); } @Test public void testReactorBasedUnlimitedRetries() { TestSubscriber<String> testSubscriber = TestSubscriber.create(); final VirtualTimeScheduler virtualTimeScheduler = VirtualTimeScheduler.create(); final Retry retryFun = builder.withUnlimitedRetries() .withReactorScheduler(virtualTimeScheduler) .withDelay(RETRY_DELAY_SEC, RETRY_DELAY_SEC * 4, TimeUnit.SECONDS) .buildRetryExponentialBackoff(); Flux.range(1, 100) .map(i -> new RuntimeException("Error " + i)) .flatMap(this::fluxOf) .retryWhen(retryFun) .subscribe(testSubscriber); virtualTimeScheduler.advanceTimeBy(Duration.ofSeconds(RETRY_DELAY_SEC * 1000)); testSubscriber.assertNoErrors(); } private Flux<String> fluxOf(Object... items) { AtomicInteger pos = new AtomicInteger(); return Flux.create(sink -> { for (int i = pos.get(); i < items.length; i++) { pos.incrementAndGet(); Object item = items[i]; if (item instanceof Throwable) { sink.error((Throwable) item); return; } sink.next((String) item); } sink.complete(); }); } private Observable<String> observableOf(Object... items) { AtomicInteger pos = new AtomicInteger(); return Observable.create(subscriber -> { for (int i = pos.get(); i < items.length; i++) { pos.incrementAndGet(); Object item = items[i]; if (item instanceof Throwable) { subscriber.onError((Throwable) item); return; } subscriber.onNext((String) item); } subscriber.onCompleted(); }); } }
557
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/rx/PeriodicGeneratorTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx; import java.util.List; import java.util.concurrent.TimeUnit; import com.netflix.titus.testkit.rx.ExtTestSubscriber; import org.junit.Test; import rx.Observable; import rx.Subscription; import rx.schedulers.Schedulers; import rx.schedulers.TestScheduler; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; public class PeriodicGeneratorTest { private static final long INITIAL_DELAY_MS = 1; private static final long INTERVAL_MS = 5; private static final Throwable SIMULATED_ERROR = new RuntimeException("simulated error"); private static final List<String> SOURCE_VALUES = asList("A", "B"); private static final Observable<String> OK_SOURCE = Observable.from(SOURCE_VALUES); private static final Observable<String> BAD_SOURCE = Observable.just("A").concatWith(Observable.error(SIMULATED_ERROR)); private final TestScheduler testScheduler = Schedulers.test(); private final ExtTestSubscriber<List<String>> testSubscriber = new ExtTestSubscriber<>(); @Test public void testOkEmitter() throws Exception { Subscription subscription = ObservableExt.periodicGenerator( OK_SOURCE, INITIAL_DELAY_MS, INTERVAL_MS, TimeUnit.MILLISECONDS, testScheduler ).subscribe(testSubscriber); assertThat(testSubscriber.takeNext()).isNull(); // Check emits expectOkEmit(INITIAL_DELAY_MS); expectOkEmit(INTERVAL_MS); expectOkEmit(INTERVAL_MS); // Unsubscribe subscription.unsubscribe(); testSubscriber.onCompleted(); } @Test public void testFailingEmitter() throws Exception { ObservableExt.periodicGenerator( BAD_SOURCE, INITIAL_DELAY_MS, INTERVAL_MS, TimeUnit.MILLISECONDS, testScheduler ).subscribe(testSubscriber); // Check emits expectBadEmit(INITIAL_DELAY_MS); } private void expectOkEmit(long delayMs) { testScheduler.advanceTimeBy(delayMs - 1, TimeUnit.MILLISECONDS); assertThat(testSubscriber.takeNext()).isNull(); testScheduler.advanceTimeBy(1, TimeUnit.MILLISECONDS); assertThat(testSubscriber.takeNext()).isEqualTo(SOURCE_VALUES); } private void expectBadEmit(long delayMs) { testScheduler.advanceTimeBy(delayMs - 1, TimeUnit.MILLISECONDS); assertThat(testSubscriber.takeNext()).isNull(); testScheduler.advanceTimeBy(1, TimeUnit.MILLISECONDS); assertThat(testSubscriber.getError()).isEqualTo(SIMULATED_ERROR); } }
558
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/rx/ReactorMapWithStateTransformerTest.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx; import java.util.ArrayList; import java.util.List; import java.util.function.Function; import com.netflix.titus.common.util.CollectionsExt; import com.netflix.titus.common.util.tuple.Pair; import com.netflix.titus.testkit.rx.TitusRxSubscriber; import org.junit.Test; import reactor.core.publisher.DirectProcessor; import reactor.core.publisher.Flux; import static com.netflix.titus.common.util.rx.ReactorExt.mapWithState; import static org.assertj.core.api.Assertions.assertThat; public class ReactorMapWithStateTransformerTest { @Test public void testStatePropagation() { List<String> all = Flux.just("a", "b") .transformDeferred(mapWithState("START", (next, state) -> Pair.of(state + " -> " + next, next))) .collectList().block(); assertThat(all).contains("START -> a", "a -> b"); } @Test public void testStatePropagationWithCleanup() { DirectProcessor<String> source = DirectProcessor.create(); DirectProcessor<Function<List<String>, Pair<String, List<String>>>> cleanupActions = DirectProcessor.create(); TitusRxSubscriber<String> testSubscriber = new TitusRxSubscriber<>(); source.transformDeferred(mapWithState( new ArrayList<>(), (next, state) -> Pair.of( String.join(",", state) + " + " + next, CollectionsExt.copyAndAdd(state, next) ), cleanupActions )).subscribe(testSubscriber); source.onNext("a"); assertThat(testSubscriber.takeNext()).isEqualTo(" + a"); source.onNext("b"); assertThat(testSubscriber.takeNext()).isEqualTo("a + b"); cleanupActions.onNext(list -> Pair.of("removed " + list.get(0), list.subList(1, list.size()))); assertThat(testSubscriber.takeNext()).isEqualTo("removed a"); source.onNext("c"); assertThat(testSubscriber.takeNext()).isEqualTo("b + c"); } }
559
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/rx/ReactorHedgedTransformerTest.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx; import java.time.Duration; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; import com.netflix.spectator.api.DefaultRegistry; import org.junit.Test; import reactor.core.publisher.Mono; import reactor.core.scheduler.Schedulers; import reactor.test.StepVerifier; import static java.util.Arrays.asList; public class ReactorHedgedTransformerTest { enum Behavior { Success, RetryableError, NotRetryableError } private static final RuntimeException SIMULATED_RETRYABLE_ERROR = new RuntimeException("simulated retryable error"); private static final RuntimeException SIMULATED_NOT_RETRYABLE_ERROR = new RuntimeException("simulated not retryable error"); private static final List<Duration> THRESHOLDS = asList(Duration.ofMillis(1), Duration.ofMillis(10), Duration.ofMillis(100)); private static final Map<String, String> CONTEXT = Collections.singletonMap("test", "123"); @Test public void testSuccess() { testSuccess(0, new Behavior[]{Behavior.Success, Behavior.RetryableError, Behavior.RetryableError, Behavior.RetryableError}); testSuccess(1, new Behavior[]{Behavior.RetryableError, Behavior.Success, Behavior.RetryableError, Behavior.RetryableError}); testSuccess(10, new Behavior[]{Behavior.RetryableError, Behavior.RetryableError, Behavior.Success, Behavior.RetryableError}); testSuccess(100, new Behavior[]{Behavior.RetryableError, Behavior.RetryableError, Behavior.RetryableError, Behavior.Success}); } private void testSuccess(long awaitMs, Behavior[] behaviors) { StepVerifier.withVirtualTime(() -> newSource(behaviors).transformDeferred(hedgeOf(THRESHOLDS))) .thenAwait(Duration.ofMillis(awaitMs)) .expectNext(1L) .verifyComplete(); } @Test public void testMonoVoidSuccess() { StepVerifier.withVirtualTime(() -> newVoidSource(new Behavior[]{Behavior.RetryableError, Behavior.Success, Behavior.RetryableError, Behavior.RetryableError}) .transformDeferred(hedgeOf(THRESHOLDS)) ) .thenAwait(Duration.ofMillis(1)) .expectComplete() .verify(); } @Test public void testFailureWithNonRetryableError() { StepVerifier.withVirtualTime(() -> newSource(new Behavior[]{Behavior.NotRetryableError, Behavior.Success, Behavior.Success, Behavior.Success}) .transformDeferred(hedgeOf(THRESHOLDS)) ) .thenAwait(Duration.ofMillis(0)) .expectErrorMatches(error -> error == SIMULATED_NOT_RETRYABLE_ERROR) .verify(); } @Test public void testConcurrent() { StepVerifier.withVirtualTime(() -> newSource(Behavior.RetryableError, Behavior.RetryableError, Behavior.RetryableError, Behavior.Success) .transformDeferred(hedgeOf(asList(Duration.ZERO, Duration.ZERO, Duration.ZERO))) ) .thenAwait(Duration.ZERO) .expectNext(1L) .verifyComplete(); } @Test public void testAllFailures() { StepVerifier.withVirtualTime(() -> newSource(Behavior.RetryableError, Behavior.RetryableError, Behavior.RetryableError, Behavior.RetryableError) .transformDeferred(hedgeOf(THRESHOLDS)) ) .thenAwait(Duration.ofMillis(100)) .expectErrorMatches(error -> error == SIMULATED_RETRYABLE_ERROR) .verify(); } @Test public void testAllMonoVoidFailures() { StepVerifier.withVirtualTime(() -> newVoidSource(Behavior.RetryableError, Behavior.RetryableError, Behavior.RetryableError, Behavior.RetryableError) .transformDeferred(hedgeOf(THRESHOLDS)) ) .thenAwait(Duration.ofMillis(100)) .expectErrorMatches(error -> error == SIMULATED_RETRYABLE_ERROR) .verify(); } private Mono<Long> newSource(Behavior... behaviors) { return newSource(1L, behaviors); } private Mono<Void> newVoidSource(Behavior... behaviors) { return newSource(null, behaviors); } private <T> Mono<T> newSource(T value, Behavior[] behaviors) { AtomicInteger indexRef = new AtomicInteger(); return Mono.defer(() -> Mono.fromCallable(() -> { int index = indexRef.getAndIncrement() % behaviors.length; switch (behaviors[index]) { case RetryableError: throw SIMULATED_RETRYABLE_ERROR; case NotRetryableError: throw SIMULATED_NOT_RETRYABLE_ERROR; case Success: } return value; }) ); } private <T> Function<Mono<T>, Mono<T>> hedgeOf(List<Duration> thresholds) { return ReactorExt.hedged( thresholds, error -> error == SIMULATED_RETRYABLE_ERROR, CONTEXT, new DefaultRegistry(), Schedulers.parallel() ); } }
560
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/rx/ReactorRetriersTest.java
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx; import java.util.Iterator; import java.util.concurrent.atomic.AtomicBoolean; import org.junit.Test; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.core.publisher.Signal; import reactor.core.publisher.SignalType; import static org.assertj.core.api.Assertions.assertThat; public class ReactorRetriersTest { @Test public void testRectorPredicateRetryer() { AtomicBoolean retryRef = new AtomicBoolean(); Iterator<Signal<String>> it = Flux.fromArray(new String[]{"a", "b", "c"}) .flatMap(value -> { if (value.equals("b")) { return Mono.error(new RuntimeException("simulated error")); } return Mono.just(value); }) .retryWhen(ReactorRetriers.rectorPredicateRetryer(error -> !retryRef.getAndSet(true))) .materialize() .toIterable() .iterator(); assertThat(it.next().get()).isEqualTo("a"); assertThat(it.next().get()).isEqualTo("a"); Signal<String> third = it.next(); assertThat(third.getType()).isEqualTo(SignalType.ON_ERROR); assertThat(third.getThrowable()).isInstanceOf(RuntimeException.class); } }
561
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/rx/PropagatorTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import com.jayway.awaitility.Awaitility; import com.jayway.awaitility.core.ConditionFactory; import com.netflix.titus.testkit.rx.ExtTestSubscriber; import org.junit.Test; import rx.Observable; import rx.Subscription; import static org.assertj.core.api.Assertions.assertThat; public class PropagatorTest { private final ExtTestSubscriber<String> subscriber1 = new ExtTestSubscriber<>(); private final ExtTestSubscriber<String> subscriber2 = new ExtTestSubscriber<>(); @Test public void testTwoOutputs() { AtomicInteger counter = new AtomicInteger(); List<Observable<String>> outputs = ObservableExt.propagate( Observable.defer(() -> Observable.just("Subscription#" + counter.incrementAndGet())), 2 ); assertThat(counter.get()).isEqualTo(0); outputs.get(0).subscribe(subscriber1); assertThat(counter.get()).isEqualTo(0); outputs.get(1).subscribe(subscriber2); assertThat(counter.get()).isEqualTo(1); assertThat(subscriber1.takeNext()).isEqualTo("Subscription#1"); assertThat(subscriber2.takeNext()).isEqualTo("Subscription#1"); subscriber1.assertOnCompleted(); subscriber2.assertOnCompleted(); } @Test public void testCancellationOfOneOutput() { List<Observable<String>> outputs = ObservableExt.propagate(Observable.never(), 2); Subscription subscription1 = outputs.get(0).subscribe(subscriber1); outputs.get(1).subscribe(subscriber2); assertThat(subscriber2.isUnsubscribed()).isFalse(); subscription1.unsubscribe(); assertThat(subscriber2.isUnsubscribed()).isTrue(); assertThat(subscriber2.getError()).isInstanceOf(IllegalStateException.class); } @Test public void testSourceEmittingError() { RuntimeException error = new RuntimeException("simulated error"); List<Observable<String>> outputs = ObservableExt.propagate( Observable.error(error), 2 ); outputs.get(0).subscribe(subscriber1); outputs.get(1).subscribe(subscriber2); subscriber1.assertOnError(error); subscriber2.assertOnError(error); } @Test public void testSourceWithTimeout() { List<Observable<String>> outputs = ObservableExt.propagate( Observable.<String>never().timeout(1, TimeUnit.MILLISECONDS), 2 ); outputs.get(0).subscribe(subscriber1); outputs.get(1).subscribe(subscriber2); await().until(() -> subscriber1.isUnsubscribed() && subscriber2.isUnsubscribed()); assertThat(subscriber1.getError()).isInstanceOf(TimeoutException.class); assertThat(subscriber2.getError()).isInstanceOf(TimeoutException.class); } private ConditionFactory await() { return Awaitility.await().timeout(30, TimeUnit.SECONDS); } }
562
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/rx/ReactorHeadTransformerTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import com.netflix.titus.testkit.rx.TitusRxSubscriber; import org.junit.After; import org.junit.Test; import reactor.core.Disposable; import reactor.core.publisher.Flux; import reactor.core.scheduler.Schedulers; import static com.jayway.awaitility.Awaitility.await; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; public class ReactorHeadTransformerTest { private static final List<String> HEAD_ITEMS = asList("A", "B"); private final AtomicBoolean terminateFlag = new AtomicBoolean(); private final List<String> emittedTicks = new CopyOnWriteArrayList<>(); private final Flux<String> hotObservable = Flux.interval(Duration.ofMillis(0), Duration.ofMillis(1), Schedulers.single()) .map(tick -> { String value = "T" + tick; emittedTicks.add(value); return value; }) .doOnTerminate(() -> terminateFlag.set(true)) .doOnCancel(() -> terminateFlag.set(true)); private final Flux<String> combined = hotObservable.transformDeferred(ReactorExt.head(() -> { while (emittedTicks.size() < 2) { // Tight loop } return HEAD_ITEMS; })); private final TitusRxSubscriber<String> testSubscriber = new TitusRxSubscriber<>(); @After public void tearDown() { testSubscriber.dispose(); } @Test public void testHotObservableBuffering() throws Exception { combined.subscribe(testSubscriber); // Wait until hot observable emits directly next item int currentTick = emittedTicks.size(); while (emittedTicks.size() == currentTick && testSubscriber.isOpen()) { } testSubscriber.failIfClosed(); assertThat(testSubscriber.isOpen()).isTrue(); int checkedCount = HEAD_ITEMS.size() + currentTick + 1; List<String> checkedSequence = testSubscriber.takeNext(checkedCount, Duration.ofSeconds(5)); testSubscriber.dispose(); await().timeout(5, TimeUnit.SECONDS).until(terminateFlag::get); List<String> expected = new ArrayList<>(HEAD_ITEMS); expected.addAll(emittedTicks.subList(0, currentTick + 1)); assertThat(checkedSequence).containsExactlyElementsOf(expected); } @Test public void testExceptionInSubscriberTerminatesSubscription() { AtomicInteger errorCounter = new AtomicInteger(); Disposable subscription = combined.subscribe( next -> { if (next.equals("T3")) { throw new RuntimeException("simulated error"); } }, e -> errorCounter.incrementAndGet() ); // Wait until hot observable emits error while (!terminateFlag.get()) { } await().timeout(5, TimeUnit.SECONDS).until(subscription::isDisposed); assertThat(errorCounter.get()).isEqualTo(1); } @Test public void testExceptionInHead() { Flux.just("A").transformDeferred(ReactorExt.head(() -> { throw new RuntimeException("Simulated error"); })).subscribe(testSubscriber); assertThat(testSubscriber.hasError()).isTrue(); } }
563
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/rx/ReactorMergeOperationsTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx; import java.util.HashSet; import java.util.Map; import java.util.Optional; import java.util.Set; import com.google.common.collect.ImmutableMap; import org.junit.Test; import reactor.core.publisher.Mono; import reactor.core.scheduler.Schedulers; import static org.assertj.core.api.Assertions.assertThat; public class ReactorMergeOperationsTest { @Test public void testMonoMerge() { Set<String> resultCollector = new HashSet<>(); Map<String, Mono<Void>> monoMap = ImmutableMap.<String, Mono<Void>>builder() .put("mono1", Mono.defer(() -> { resultCollector.add("mono1"); return Mono.empty(); })) .put("mono2", Mono.defer(() -> { resultCollector.add("mono2"); return Mono.empty(); })) .build(); Map<String, Optional<Throwable>> executionResult = ReactorExt.merge(monoMap, 2, Schedulers.parallel()).block(); assertThat(executionResult).hasSize(2); assertThat(executionResult.get("mono1")).isEmpty(); assertThat(executionResult.get("mono2")).isEmpty(); assertThat(resultCollector).contains("mono1", "mono2"); } @Test public void testMonoMergeWithError() { Map<String, Mono<Void>> monoMap = ImmutableMap.<String, Mono<Void>>builder() .put("mono1", Mono.defer(Mono::empty)) .put("mono2", Mono.defer(() -> Mono.error(new RuntimeException("Simulated error")))) .put("mono3", Mono.defer(Mono::empty)) .build(); Map<String, Optional<Throwable>> executionResult = ReactorExt.merge(monoMap, 2, Schedulers.parallel()).block(); assertThat(executionResult).hasSize(3); assertThat(executionResult.get("mono1")).isEmpty(); assertThat(executionResult.get("mono2")).containsInstanceOf(RuntimeException.class); assertThat(executionResult.get("mono3")).isEmpty(); } }
564
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/rx/HeadTransformerTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import com.netflix.titus.testkit.rx.ExtTestSubscriber; import org.junit.After; import org.junit.Test; import rx.Observable; import rx.Subscription; import rx.schedulers.Schedulers; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; public class HeadTransformerTest { private static final List<String> HEAD_ITEMS = asList("A", "B"); private final AtomicBoolean terminateFlag = new AtomicBoolean(); private final List<String> emittedTicks = new CopyOnWriteArrayList<>(); private final Observable<String> hotObservable = Observable.interval(0, 1, TimeUnit.MILLISECONDS, Schedulers.io()) .map(tick -> { String value = "T" + tick; emittedTicks.add(value); return value; }) .doOnTerminate(() -> terminateFlag.set(true)) .doOnUnsubscribe(() -> terminateFlag.set(true)); private final Observable<String> combined = hotObservable.compose(ObservableExt.head(() -> { while (emittedTicks.size() < 2) { // Tight loop } return HEAD_ITEMS; })); private final ExtTestSubscriber<String> testSubscriber = new ExtTestSubscriber<>(); @After public void tearDown() throws Exception { testSubscriber.unsubscribe(); } @Test public void testHotObservableBuffering() throws Exception { Subscription subscription = combined.subscribe(testSubscriber); // Wait until hot observable emits directly next item int currentTick = emittedTicks.size(); while (emittedTicks.size() == currentTick) { } int checkedCount = HEAD_ITEMS.size() + currentTick + 1; List<String> checkedSequence = testSubscriber.takeNext(checkedCount, 5, TimeUnit.SECONDS); testSubscriber.unsubscribe(); assertThat(terminateFlag.get()).isTrue(); assertThat(subscription.isUnsubscribed()).isTrue(); List<String> expected = new ArrayList<>(HEAD_ITEMS); expected.addAll(emittedTicks.subList(0, currentTick + 1)); assertThat(checkedSequence).containsExactlyElementsOf(expected); } @Test public void testExceptionInSubscriberTerminatesSubscription() throws Exception { AtomicInteger errorCounter = new AtomicInteger(); Subscription subscription = combined.subscribe( next -> { if (next.equals("T3")) { throw new RuntimeException("simulated error"); } }, e -> errorCounter.incrementAndGet() ); // Wait until hot observable emits error while (!terminateFlag.get()) { } assertThat(terminateFlag.get()).isTrue(); assertThat(subscription.isUnsubscribed()).isTrue(); } @Test public void testExceptionInHead() throws Exception { Observable.just("A").compose(ObservableExt.head(() -> { throw new RuntimeException("Simulated error"); })).subscribe(testSubscriber); testSubscriber.assertOnError(); } }
565
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/rx/ReactorExtTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx; import java.util.Optional; import org.junit.Test; import reactor.core.publisher.Mono; import static org.assertj.core.api.Assertions.assertThat; public class ReactorExtTest { @Test public void testEmitValue() { Optional<Throwable> error = ReactorExt.emitError(Mono.just("Hello")).block(); assertThat(error).isEmpty(); } @Test public void testEmitError() { Optional<Throwable> error = ReactorExt.emitError(Mono.error(new RuntimeException("SimulatedError"))).single().block(); assertThat(error).isPresent(); assertThat(error.get()).isInstanceOf(RuntimeException.class); } }
566
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/rx/ReEmitterTransformerTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx; import java.util.concurrent.TimeUnit; import com.netflix.titus.testkit.rx.ExtTestSubscriber; import org.junit.Before; import org.junit.Test; import rx.schedulers.Schedulers; import rx.schedulers.TestScheduler; import rx.subjects.PublishSubject; import static org.assertj.core.api.Assertions.assertThat; public class ReEmitterTransformerTest { private static final long INTERVAL_MS = 1_000; public final TestScheduler testScheduler = Schedulers.test(); private final PublishSubject<String> subject = PublishSubject.create(); private final ExtTestSubscriber<String> subscriber = new ExtTestSubscriber<>(); @Before public void setUp() { subject.compose(ObservableExt.reemiter(String::toLowerCase, INTERVAL_MS, TimeUnit.MILLISECONDS, testScheduler)).subscribe(subscriber); } @Test public void testReemits() { // Until first item is emitted, there is nothing to re-emit. advanceSteps(2); assertThat(subscriber.takeNext()).isNull(); // Emit 'A' and wait for re-emit subject.onNext("A"); assertThat(subscriber.takeNext()).isEqualTo("A"); advanceSteps(1); assertThat(subscriber.takeNext()).isEqualTo("a"); // Emit 'B' and wait for re-emit subject.onNext("B"); assertThat(subscriber.takeNext()).isEqualTo("B"); advanceSteps(1); assertThat(subscriber.takeNext()).isEqualTo("b"); } @Test public void testNoReemits() { subject.onNext("A"); assertThat(subscriber.takeNext()).isEqualTo("A"); testScheduler.advanceTimeBy(INTERVAL_MS - 1, TimeUnit.MILLISECONDS); assertThat(subscriber.takeNext()).isNull(); subject.onNext("B"); assertThat(subscriber.takeNext()).isEqualTo("B"); testScheduler.advanceTimeBy(INTERVAL_MS - 1, TimeUnit.MILLISECONDS); assertThat(subscriber.takeNext()).isNull(); } private void advanceSteps(int steps) { testScheduler.advanceTimeBy(steps * INTERVAL_MS, TimeUnit.MILLISECONDS); } }
567
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/rx/MapWithStateTransformerTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx; import java.util.ArrayList; import java.util.List; import java.util.function.Function; import java.util.stream.Collectors; import com.netflix.titus.common.util.CollectionsExt; import com.netflix.titus.common.util.tuple.Pair; import com.netflix.titus.testkit.rx.ExtTestSubscriber; import org.junit.Test; import rx.Observable; import rx.subjects.PublishSubject; import static com.netflix.titus.common.util.rx.ObservableExt.mapWithState; import static org.assertj.core.api.Assertions.assertThat; public class MapWithStateTransformerTest { @Test public void testStatePropagation() throws Exception { List<String> all = Observable.just("a", "b") .compose(mapWithState("START", (next, state) -> Pair.of(state + " -> " + next, next))) .toList().toBlocking().first(); assertThat(all).contains("START -> a", "a -> b"); } @Test public void testStatePropagationWithCleanup() throws Exception { PublishSubject<String> source = PublishSubject.create(); PublishSubject<Function<List<String>, Pair<String, List<String>>>> cleanupActions = PublishSubject.create(); ExtTestSubscriber<String> testSubscriber = new ExtTestSubscriber<>(); source.compose(mapWithState(new ArrayList<>(), (next, state) -> Pair.of( state.stream().collect(Collectors.joining(",")) + " + " + next, CollectionsExt.copyAndAdd(state, next) ), cleanupActions )).subscribe(testSubscriber); source.onNext("a"); assertThat(testSubscriber.takeNext()).isEqualTo(" + a"); source.onNext("b"); assertThat(testSubscriber.takeNext()).isEqualTo("a + b"); cleanupActions.onNext(list -> Pair.of("removed " + list.get(0), list.subList(1, list.size()))); assertThat(testSubscriber.takeNext()).isEqualTo("removed a"); source.onNext("c"); assertThat(testSubscriber.takeNext()).isEqualTo("b + c"); } }
568
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/rx/ObservableExtTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx; import com.netflix.titus.testkit.rx.ExtTestSubscriber; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; import rx.Observable; import rx.schedulers.Schedulers; import rx.schedulers.TestScheduler; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; public class ObservableExtTest { private static final int DELAY_MS = 100; private final TestScheduler testScheduler = Schedulers.test(); private final ExtTestSubscriber<Object> testSubscriber = new ExtTestSubscriber<>(); private final Object A = new Object(), B = new Object(), C = new Object(), D = new Object(), E = new Object(), F = new Object(); @Test public void testFromWithDelayEmpty() { final List<Observable<Object>> chunks = Collections.emptyList(); Observable<Object> observable = ObservableExt.fromWithDelay(chunks, DELAY_MS, TimeUnit.MILLISECONDS, testScheduler); observable = observable.defaultIfEmpty(B); observable.subscribe(testSubscriber); assertThat(testSubscriber.takeNext()).isSameAs(B); assertThat(testSubscriber.takeNext()).isNull(); } @Test public void testFromWithDelaySingle() { final List<Observable<Object>> chunks = Collections.singletonList(Observable.just(A)); Observable<Object> observable = ObservableExt.fromWithDelay(chunks, DELAY_MS, TimeUnit.MILLISECONDS, testScheduler); observable = observable.defaultIfEmpty(B); observable.subscribe(testSubscriber); assertThat(testSubscriber.takeNext()).isSameAs(A); assertThat(testSubscriber.takeNext()).isNull(); } @Test public void testFromWithDelayMultiple() { final List<Observable<Object>> chunks = Arrays.asList( Observable.just(A).delay(1, TimeUnit.MILLISECONDS, testScheduler), Observable.just(B, C, D), Observable.just(E)); Observable<Object> observable = ObservableExt.fromWithDelay(chunks, DELAY_MS, TimeUnit.MILLISECONDS, testScheduler); observable = observable.defaultIfEmpty(B); observable.subscribe(testSubscriber); // Nothing is available yet. The first element arrives after 1 ms because // of the delay on the just(A). assertThat(testSubscriber.takeNext()).isNull(); assertThat(1).isLessThan(DELAY_MS); testScheduler.advanceTimeBy(1, TimeUnit.MILLISECONDS); // Now that we've waited the 1 ms delay, A should be available. Note // that fromWithDelay() should not delay the first element by DELAY_MS. assertThat(testSubscriber.takeNext()).isSameAs(A); assertThat(testSubscriber.takeNext()).isNull(); testScheduler.advanceTimeBy(DELAY_MS, TimeUnit.MILLISECONDS); assertThat(testSubscriber.takeNext()).isSameAs(B); assertThat(testSubscriber.takeNext()).isSameAs(C); assertThat(testSubscriber.takeNext()).isSameAs(D); assertThat(testSubscriber.takeNext()).isNull(); testScheduler.advanceTimeBy(DELAY_MS, TimeUnit.MILLISECONDS); assertThat(testSubscriber.takeNext()).isSameAs(E); assertThat(testSubscriber.takeNext()).isNull(); } @Test public void testFromWithDelayHundreds() { final int NUM_CHUNKS_TO_TEST = 300; final List<Observable<Integer>> chunks = new ArrayList<>(NUM_CHUNKS_TO_TEST); for (int i = 0; i < NUM_CHUNKS_TO_TEST; ++i) { chunks.add(Observable.just(i).delay(1000, TimeUnit.MILLISECONDS, testScheduler)); } Observable<Integer> observable = ObservableExt.fromWithDelay(chunks, DELAY_MS, TimeUnit.MILLISECONDS, testScheduler); observable = observable.defaultIfEmpty(-1); observable.subscribe(testSubscriber); assertThat(testSubscriber.takeNext()).isNull(); for (int i = 0; i < NUM_CHUNKS_TO_TEST; ++i) { if (i > 0) testScheduler.advanceTimeBy(DELAY_MS, TimeUnit.MILLISECONDS); testScheduler.advanceTimeBy(1000, TimeUnit.MILLISECONDS); assertThat(testSubscriber.takeNext()).isEqualTo(i); assertThat(testSubscriber.takeNext()).isNull(); } } }
569
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/rx/eventbus
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/rx/eventbus/internal/DefaultRxEventBusTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx.eventbus.internal; import java.util.concurrent.atomic.AtomicBoolean; import com.netflix.spectator.api.DefaultRegistry; import com.netflix.spectator.api.Registry; import com.netflix.titus.common.util.rx.eventbus.RxEventBus; import com.netflix.titus.testkit.junit.resource.Log4jExternalResource; import com.netflix.titus.testkit.rx.ExtTestSubscriber; import org.junit.After; import org.junit.Rule; import org.junit.Test; import rx.Subscriber; import rx.schedulers.Schedulers; import rx.schedulers.TestScheduler; import static org.assertj.core.api.Assertions.assertThat; public class DefaultRxEventBusTest { private static final long MAX_QUEUE_SIZE = 1; @Rule public final Log4jExternalResource loggingActivator = Log4jExternalResource.enableFor(DefaultRxEventBus.class); private final TestScheduler testScheduler = Schedulers.test(); private final Registry registry = new DefaultRegistry(); private final RxEventBus eventBus = new DefaultRxEventBus(registry.createId("test"), registry, MAX_QUEUE_SIZE, testScheduler); @After public void tearDown() throws Exception { eventBus.close(); } @Test public void testDirectEventPublishing() throws Exception { ExtTestSubscriber<String> testSubscriber = new ExtTestSubscriber<>(); eventBus.listen("myClient", String.class).subscribe(testSubscriber); eventBus.publish("event1"); assertThat(testSubscriber.takeNext()).isEqualTo("event1"); assertThat(testSubscriber.takeNext()).isNull(); } @Test public void testAsyncEventPublishing() throws Exception { ExtTestSubscriber<String> testSubscriber = new ExtTestSubscriber<>(); eventBus.listen("myClient", String.class).subscribe(testSubscriber); assertThat(testSubscriber.takeNext()).isNull(); eventBus.publishAsync("event1"); testScheduler.triggerActions(); assertThat(testSubscriber.takeNext()).isEqualTo("event1"); assertThat(testSubscriber.takeNext()).isNull(); } @Test public void testEventBusCloseTerminatesSubscriptions() throws Exception { ExtTestSubscriber<String> testSubscriber = new ExtTestSubscriber<>(); eventBus.listen("myClient", String.class).subscribe(testSubscriber); eventBus.close(); testSubscriber.assertOnCompleted(); } @Test public void testSlowConsumerTerminatesWithOverflowError() throws Exception { AtomicBoolean failed = new AtomicBoolean(); Subscriber<String> slowSubscriber = new Subscriber<String>() { @Override public void onStart() { request(0); } @Override public void onCompleted() { } @Override public void onError(Throwable e) { failed.set(true); } @Override public void onNext(String s) { } }; eventBus.listen("myClient", String.class).subscribe(slowSubscriber); for (int i = 0; i <= MAX_QUEUE_SIZE; i++) { eventBus.publish("event" + i); } assertThat(failed.get()).isTrue(); assertThat(slowSubscriber.isUnsubscribed()).isTrue(); } }
570
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/rx
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/rx/invoker/ReactorSerializedInvokerTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx.invoker; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import com.netflix.spectator.api.DefaultRegistry; import com.netflix.titus.common.util.time.Clocks; import org.junit.After; import org.junit.Test; import reactor.core.Disposable; import reactor.core.publisher.Mono; import reactor.core.scheduler.Schedulers; import static com.jayway.awaitility.Awaitility.await; import static org.assertj.core.api.Assertions.assertThat; public class ReactorSerializedInvokerTest { private static final Duration QUEUEING_TIMEOUT = Duration.ofMillis(500); private static final Duration EXCESSIVE_RUNNING_TIME = Duration.ofMillis(1_000); private ReactorSerializedInvoker<String> reactorSerializedInvoker = ReactorSerializedInvoker.<String>newBuilder() .withName("test") .withScheduler(Schedulers.parallel()) .withMaxQueueSize(10) .withExcessiveRunningTime(EXCESSIVE_RUNNING_TIME) .withRegistry(new DefaultRegistry()) .withClock(Clocks.system()) .build(); @After public void tearDown() { reactorSerializedInvoker.shutdown(Duration.ofSeconds(1)); } @Test(timeout = 5_000) public void testInlineAction() { List<String> result = new CopyOnWriteArrayList<>(); for (int i = 0; i < 5; i++) { int index = i; reactorSerializedInvoker.submit(Mono.just("#" + index).map(tick -> "#" + index)).subscribe(result::add); } await().until(() -> result.size() == 5); assertThat(result).contains("#0", "#1", "#2", "#3", "#4"); } @Test(timeout = 5_000) public void testLongAsynchronousAction() { List<String> result = new CopyOnWriteArrayList<>(); for (int i = 0; i < 5; i++) { int index = i; reactorSerializedInvoker.submit(Mono.delay(Duration.ofMillis(10)).map(tick -> "#" + index)).subscribe(result::add); } await().until(() -> result.size() == 5); assertThat(result).contains("#0", "#1", "#2", "#3", "#4"); } @Test(expected = RuntimeException.class, timeout = 5_000) public void testErrorAction() { reactorSerializedInvoker.submit(Mono.error(new RuntimeException("Simulated error"))).block(); } @Test(timeout = 5_000) public void testQueueingTimeOut() { List<String> result = new CopyOnWriteArrayList<>(); AtomicReference<Throwable> errorRef = new AtomicReference<>(); reactorSerializedInvoker.submit(Mono.delay(Duration.ofHours(1)).timeout(QUEUEING_TIMEOUT).map(tick -> "First")).subscribe( result::add, errorRef::set ); reactorSerializedInvoker.submit(Mono.just("Second")).subscribe(result::add, errorRef::set); await().until(() -> result.size() == 1 && errorRef.get() != null); assertThat(result.get(0)).isEqualTo("Second"); } @Test(timeout = 5_000) public void testExcessiveRunningTime() { AtomicReference<Object> resultRef = new AtomicReference<>(); Disposable disposable = reactorSerializedInvoker.submit(Mono.delay(Duration.ofHours(1)).map(tick -> "First")).subscribe( resultRef::set, resultRef::set ); await().until(disposable::isDisposed); assertThat(resultRef.get()).isInstanceOf(TimeoutException.class); } @Test(timeout = 5_000) public void testCancellation() { AtomicReference<Object> resultRef = new AtomicReference<>(); Disposable disposable = reactorSerializedInvoker.submit(Mono.delay(Duration.ofHours(1)).map(tick -> "First")) .doOnCancel(() -> resultRef.set("CANCELLED")) .subscribe( resultRef::set, resultRef::set ); disposable.dispose(); await().until(disposable::isDisposed); assertThat(resultRef.get()).isEqualTo("CANCELLED"); } @Test(timeout = 5_000) public void testShutdown() { List<Disposable> disposables = new ArrayList<>(); AtomicInteger errors = new AtomicInteger(); for (int i = 0; i < 5; i++) { int index = i; Disposable disposable = reactorSerializedInvoker.submit(Mono.delay(Duration.ofHours(1)).map(tick -> "#" + index)) .doFinally(signalType -> errors.incrementAndGet()) .subscribe( next -> { }, e -> { } ); disposables.add(disposable); } reactorSerializedInvoker.shutdown(Duration.ofSeconds(5)); await().until(() -> disposables.stream().map(Disposable::isDisposed).reduce(true, (a, b) -> a && b)); assertThat(errors.get()).isEqualTo(5); } }
571
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/rx
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/rx/batch/BatchableOperationMock.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx.batch; import java.time.Instant; class BatchableOperationMock implements Batchable<String> { private final Priority priority; private final Instant timestamp; private final String resourceId; private final String subResourceId; private final String state; private final String identifier; BatchableOperationMock(Priority priority, Instant timestamp, String resourceId, String subResourceId, String state) { this.priority = priority; this.timestamp = timestamp; this.resourceId = resourceId; this.subResourceId = subResourceId; this.state = state; this.identifier = resourceId + "-" + subResourceId; } /** * Updates are applied to a (resourceId, subResourceId) pair. * * @return the resourceId */ @Override public String getIdentifier() { return identifier; } @Override public Priority getPriority() { return priority; } @Override public Instant getTimestamp() { return timestamp; } public String getResourceId() { return resourceId; } @Override public boolean isEquivalent(Batchable<?> other) { if (!(other instanceof BatchableOperationMock)) { return false; } BatchableOperationMock otherMock = (BatchableOperationMock) other; return priority.equals(otherMock.priority) && resourceId.equals(otherMock.resourceId) && subResourceId.equals(otherMock.subResourceId) && state.equals(otherMock.state); } }
572
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/rx
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/rx/batch/RateLimitedBatcherTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx.batch; import java.time.Instant; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import com.netflix.spectator.api.NoopRegistry; import com.netflix.titus.common.util.limiter.tokenbucket.RefillStrategy; import com.netflix.titus.common.util.limiter.tokenbucket.TokenBucket; import org.assertj.core.api.Assertions; import org.junit.Before; import org.junit.Test; import rx.Observable; import rx.Subscriber; import rx.observers.AssertableSubscriber; import rx.schedulers.Schedulers; import rx.schedulers.TestScheduler; import rx.subjects.PublishSubject; import rx.subjects.Subject; import static com.netflix.titus.common.util.rx.batch.Priority.HIGH; import static com.netflix.titus.common.util.rx.batch.Priority.LOW; import static java.time.Duration.ofHours; import static java.time.Duration.ofMillis; import static java.time.Duration.ofSeconds; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class RateLimitedBatcherTest { private TestScheduler testScheduler; private int minimumTimeInQueueMs; private int timeWindowBucketSizeMs; private EmissionStrategy strategy; private TokenBucket tokenBucket; private Random random; @Before public void setUp() { testScheduler = Schedulers.test(); timeWindowBucketSizeMs = 1_000; minimumTimeInQueueMs = 1_000; strategy = new LargestPerTimeBucket(minimumTimeInQueueMs, timeWindowBucketSizeMs, testScheduler); RefillStrategy refillStrategy = mock(RefillStrategy.class); when(refillStrategy.getTimeUntilNextRefill(any())).thenAnswer( invocation -> invocation.<TimeUnit>getArgument(0).convert(1_000, TimeUnit.MILLISECONDS) ); tokenBucket = mock(TokenBucket.class); when(tokenBucket.getRefillStrategy()).thenReturn(refillStrategy); when(tokenBucket.tryTake()).thenReturn(true); random = new Random(); } /** * 1. older (bucketized) first * 2. in each bucket, larger batches first */ @Test public void emitAccordingToStrategy() { final int initialDelay = minimumTimeInQueueMs; final Instant now = Instant.ofEpochMilli(testScheduler.now()); final Instant start = now.minus(ofHours(1)); final Instant firstBucket = start.plus(ofMillis(timeWindowBucketSizeMs)); final Instant secondBucket = firstBucket.plus(ofMillis(timeWindowBucketSizeMs)); final RateLimitedBatcher<BatchableOperationMock, String> batcher = buildBatcher(initialDelay); final List<Batch<BatchableOperationMock, String>> expected = Arrays.asList( // older bucket Batch.of("resource1", new BatchableOperationMock(LOW, start, "resource1", "sub1", "create"), new BatchableOperationMock(LOW, randomWithinBucket(start), "resource1", "sub2", "create"), new BatchableOperationMock(LOW, randomWithinBucket(firstBucket), "resource1", "sub3", "create"), new BatchableOperationMock(LOW, randomWithinBucket(secondBucket), "resource1", "sub4", "create") ), // larger in firstBucket Batch.of("resource2", new BatchableOperationMock(LOW, randomWithinBucket(firstBucket), "resource2", "sub1", "create"), new BatchableOperationMock(LOW, randomWithinBucket(firstBucket), "resource2", "sub2", "create"), new BatchableOperationMock(LOW, randomWithinBucket(secondBucket), "resource2", "sub3", "create") ), // larger in secondBucket Batch.of("resource3", new BatchableOperationMock(LOW, randomWithinBucket(secondBucket), "resource3", "sub1", "create"), new BatchableOperationMock(LOW, randomWithinBucket(secondBucket), "resource3", "sub2", "create"), new BatchableOperationMock(LOW, randomWithinBucket(secondBucket), "resource3", "sub3", "create") ), // last Batch.of("resource4", new BatchableOperationMock(LOW, randomWithinBucket(secondBucket), "resource4", "sub1", "create"), new BatchableOperationMock(LOW, randomWithinBucket(secondBucket), "resource4", "sub2", "create") ) ); final AssertableSubscriber<Batch<BatchableOperationMock, String>> subscriber = Observable.from(toUpdateList(expected)) .lift(batcher) .test(); testScheduler.advanceTimeBy(initialDelay, TimeUnit.MILLISECONDS); subscriber.assertNoErrors() .assertValueCount(expected.size()) .assertCompleted(); final List<Batch<BatchableOperationMock, String>> events = subscriber.getOnNextEvents(); Assertions.assertThat(events).hasSize(expected.size()); for (int i = 0; i < expected.size(); i++) { final Batch<BatchableOperationMock, String> actual = events.get(i); final Batch<BatchableOperationMock, String> expectedBatch = expected.get(i); final List<BatchableOperationMock> expectedUpdates = expectedBatch.getItems(); final BatchableOperationMock[] expectedUpdatesArray = expectedUpdates.toArray(new BatchableOperationMock[expectedUpdates.size()]); assertThat(actual).isNotNull(); assertThat(actual.getIndex()).isEqualTo(expectedBatch.getIndex()); assertThat(actual.getItems()).containsExactlyInAnyOrder(expectedUpdatesArray); } } @Test public void exponentialBackoffWhenRateLimited() { when(tokenBucket.tryTake()).thenReturn(false); final int initialDelayMs = 1_000; final int maxDelayMs = 10 * initialDelayMs; final List<Integer> delays = Arrays.asList(initialDelayMs, 2 * initialDelayMs, 4 * initialDelayMs, 8 * initialDelayMs, maxDelayMs); final long afterAllDelays = delays.stream().mapToLong(Integer::longValue).sum() + 2 * maxDelayMs /* two extra round at the end */; final RateLimitedBatcher<BatchableOperationMock, String> batcher = buildBatcher(initialDelayMs, maxDelayMs); final Instant now = Instant.ofEpochMilli(testScheduler.now()); final BatchableOperationMock update = new BatchableOperationMock(LOW, now.minus(ofSeconds(5)), "resource1", "sub1", "create"); final BatchableOperationMock updateAfterDelays = new BatchableOperationMock(LOW, now.plus(ofMillis(afterAllDelays)), "resource2", "sub1", "create"); final Observable<BatchableOperationMock> updates = Observable.from(Arrays.asList(update, updateAfterDelays)); final AssertableSubscriber<Batch<BatchableOperationMock, String>> subscriber = updates.lift(batcher).test(); int attempts = 0; for (int delay : delays) { testScheduler.advanceTimeBy(delay - 1, TimeUnit.MILLISECONDS); verify(tokenBucket, times(attempts)).tryTake(); subscriber.assertNoTerminalEvent().assertNoValues(); // after a delay, we try again testScheduler.advanceTimeBy(1, TimeUnit.MILLISECONDS); verify(tokenBucket, times(++attempts)).tryTake(); subscriber.assertNoTerminalEvent().assertNoValues(); } // capped by maxDelayMs testScheduler.advanceTimeBy(maxDelayMs - 1, TimeUnit.MILLISECONDS); verify(tokenBucket, times(attempts)).tryTake(); subscriber.assertNoTerminalEvent().assertNoValues(); testScheduler.advanceTimeBy(1, TimeUnit.MILLISECONDS); verify(tokenBucket, times(++attempts)).tryTake(); subscriber.assertNoTerminalEvent().assertNoValues(); // stop being rate limited when(tokenBucket.tryTake()).thenReturn(true); testScheduler.advanceTimeBy(maxDelayMs, TimeUnit.MILLISECONDS); verify(tokenBucket, times(++attempts)).tryTake(); //noinspection unchecked subscriber.assertNoErrors() .assertValueCount(1) .assertValuesAndClear(Batch.of("resource1", update)); // delay is reset after stopped being rate limited testScheduler.advanceTimeBy(initialDelayMs, TimeUnit.MILLISECONDS); verify(tokenBucket, times(++attempts)).tryTake(); //noinspection unchecked subscriber.assertNoErrors() .assertValueCount(1) .assertValuesAndClear(Batch.of("resource2", updateAfterDelays)) .assertCompleted(); } @Test public void pendingItemsAreFlushedAfterUpstreamCompletes() { final RateLimitedBatcher<BatchableOperationMock, String> batcher = buildBatcher(minimumTimeInQueueMs); final Instant now = Instant.ofEpochMilli(testScheduler.now()); final BatchableOperationMock first = new BatchableOperationMock(LOW, now.minus(ofSeconds(5)), "resource1", "sub1", "create"); final BatchableOperationMock second = new BatchableOperationMock(LOW, now.minus(ofSeconds(3)), "resource2", "sub1", "create"); final Observable<BatchableOperationMock> updates = Observable.from(Arrays.asList(first, second)); final AssertableSubscriber<Batch<BatchableOperationMock, String>> subscriber = updates.lift(batcher).test(); testScheduler.advanceTimeBy(1, TimeUnit.MINUTES); //noinspection unchecked subscriber.assertNoErrors() .assertValueCount(2) .assertValues( Batch.of("resource1", Collections.singletonList(first)), Batch.of("resource2", Collections.singletonList(second)) ) .assertCompleted(); } @Test public void minimumTimeInQueue() { final RateLimitedBatcher<BatchableOperationMock, String> batcher = buildBatcher(1); final Instant now = Instant.ofEpochMilli(testScheduler.now()); final List<BatchableOperationMock> updatesList = Arrays.asList( new BatchableOperationMock(LOW, now, "resource1", "sub2", "create"), new BatchableOperationMock(LOW, now.minus(ofMillis(minimumTimeInQueueMs + 1)), "resource1", "sub1", "create") ); final AssertableSubscriber<Batch<BatchableOperationMock, String>> subscriber = Observable.from(updatesList).lift(batcher).test(); testScheduler.triggerActions(); subscriber.assertNoTerminalEvent().assertNoValues(); testScheduler.advanceTimeBy(1, TimeUnit.MILLISECONDS); subscriber.assertNoErrors() .assertValueCount(1) .assertValue(Batch.of("resource1", updatesList)) .assertCompleted(); } @Test public void keepUpdatesWithHighestPriorityInEachBatch() { final Instant now = Instant.ofEpochMilli(testScheduler.now()); final Instant moreRecent = now.plus(ofMillis(1)); final BatchableOperationMock lowPriority = new BatchableOperationMock(LOW, moreRecent, "resource3", "sub2", "create"); final BatchableOperationMock highPriority = new BatchableOperationMock(HIGH, now, "resource3", "sub2", "remove"); assertEmitSingleAfterReceiving(highPriority, lowPriority, highPriority); } @Test public void keepMostRecentUpdatesInEachBatch() { final Instant now = Instant.ofEpochMilli(testScheduler.now()); final Instant moreRecent = now.plus(ofMillis(1)); final BatchableOperationMock old = new BatchableOperationMock(LOW, now, "resource2", "sub2", "create"); final BatchableOperationMock recent = new BatchableOperationMock(LOW, moreRecent, "resource2", "sub2", "remove"); assertEmitSingleAfterReceiving(recent, old, recent); } @Test public void doNotReplaceOlderUpdatesDoingTheSame() { final Instant now = Instant.ofEpochMilli(testScheduler.now()); final Instant moreRecent = now.plus(ofSeconds(10)); final BatchableOperationMock old = new BatchableOperationMock(LOW, now, "resource1", "sub2", "create"); final BatchableOperationMock recentDoingTheSame = new BatchableOperationMock(LOW, moreRecent, "resource1", "sub2", "create"); assertEmitSingleAfterReceiving(old, old, recentDoingTheSame); } private void assertEmitSingleAfterReceiving(BatchableOperationMock expected, BatchableOperationMock... receiving) { final RateLimitedBatcher<BatchableOperationMock, String> batcher = buildBatcher(minimumTimeInQueueMs); final Subject<BatchableOperationMock, BatchableOperationMock> updates = PublishSubject.<BatchableOperationMock>create().toSerialized(); final AssertableSubscriber<Batch<BatchableOperationMock, String>> subscriber = updates.lift(batcher).test(); testScheduler.triggerActions(); subscriber.assertNoTerminalEvent().assertNoValues(); for (BatchableOperationMock received : receiving) { updates.onNext(received); } testScheduler.advanceTimeBy(2 * minimumTimeInQueueMs, TimeUnit.MILLISECONDS); subscriber.assertNoErrors() .assertValueCount(1) .assertValue(Batch.of(expected.getResourceId(), Collections.singletonList(expected))); } @Test public void onCompletedIsNotSentAfterOnError() { final RateLimitedBatcher<BatchableOperationMock, String> batcher = buildBatcher(minimumTimeInQueueMs); final Subject<BatchableOperationMock, BatchableOperationMock> updates = PublishSubject.<BatchableOperationMock>create().toSerialized(); final AssertableSubscriber<Batch<BatchableOperationMock, String>> subscriber = updates.lift(batcher).test(); testScheduler.triggerActions(); subscriber.assertNoTerminalEvent().assertNoValues(); updates.onError(new RuntimeException("some problem")); testScheduler.triggerActions(); // onError is forwarded right away (i.e.: don't wait for the next flush event) subscriber.assertNotCompleted().assertError(RuntimeException.class); updates.onCompleted(); subscriber.assertNotCompleted(); } @Test public void onErrorIsNotSentAfterOnCompleted() { final RateLimitedBatcher<BatchableOperationMock, String> batcher = buildBatcher(minimumTimeInQueueMs); final Subject<BatchableOperationMock, BatchableOperationMock> updates = PublishSubject.<BatchableOperationMock>create().toSerialized(); final AssertableSubscriber<Batch<BatchableOperationMock, String>> subscriber = updates.lift(batcher).test(); testScheduler.triggerActions(); subscriber.assertNoTerminalEvent().assertNoValues(); updates.onCompleted(); // onCompleted is sent after pending items are drained testScheduler.advanceTimeBy(minimumTimeInQueueMs, TimeUnit.MILLISECONDS); subscriber.assertNoErrors().assertCompleted(); updates.onError(new RuntimeException("some problem")); subscriber.assertNoErrors(); } @Test public void ignoreErrorsFromDownstream() { final Instant now = Instant.ofEpochMilli(testScheduler.now()); final RateLimitedBatcher<BatchableOperationMock, String> batcher = buildBatcher(minimumTimeInQueueMs); final Subject<BatchableOperationMock, BatchableOperationMock> updates = PublishSubject.<BatchableOperationMock>create().toSerialized(); final AssertableSubscriber<?> subscriber = updates.lift(batcher) .lift(new ExceptionThrowingOperator("some error happened")) .test(); testScheduler.triggerActions(); subscriber.assertNoTerminalEvent().assertNoValues(); for (int i = 0; i < 10; i++) { updates.onNext(new BatchableOperationMock(LOW, now, "resource2", "sub2", "create")); testScheduler.advanceTimeBy(minimumTimeInQueueMs, TimeUnit.MILLISECONDS); subscriber.assertNoTerminalEvent().assertNoValues(); } updates.onCompleted(); testScheduler.advanceTimeBy(minimumTimeInQueueMs, TimeUnit.MILLISECONDS); subscriber.assertNoValues().assertCompleted(); } private <T extends Batchable<I>, I> List<T> toUpdateList(List<Batch<T, I>> expected) { List<T> updates = expected.stream() .flatMap(batch -> batch.getItems().stream()) .collect(Collectors.toList()); Collections.shuffle(updates); // ensure we don't rely on the ordering of updates return updates; } private Instant randomWithinBucket(Instant when) { return when.plus(ofMillis(random.nextInt(timeWindowBucketSizeMs))); } private RateLimitedBatcher<BatchableOperationMock, String> buildBatcher(long initialDelayMs) { return buildBatcher(initialDelayMs, Long.MAX_VALUE); } private RateLimitedBatcher<BatchableOperationMock, String> buildBatcher(long initialDelayMs, long maxDelayMs) { return RateLimitedBatcher.create(tokenBucket, initialDelayMs, maxDelayMs, BatchableOperationMock::getResourceId, strategy, "testBatcher", new NoopRegistry(), testScheduler); } private static class ExceptionThrowingOperator implements Observable.Operator<Object, Batch<?, ?>> { private final String errorMessage; private ExceptionThrowingOperator(String errorMessage) { this.errorMessage = errorMessage; } @Override public Subscriber<? super Batch<?, ?>> call(Subscriber<? super Object> child) { return new Subscriber<Batch<?, ?>>() { @Override public void onCompleted() { child.onCompleted(); } @Override public void onError(Throwable e) { child.onError(e); } @Override public void onNext(Batch<?, ?> batch) { throw new RuntimeException(errorMessage); } }; } } }
573
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/rx
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/rx/batch/LargestPerTimeBucketTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx.batch; import java.time.Instant; import java.util.Queue; import java.util.stream.Stream; import org.assertj.core.api.Assertions; import org.junit.Before; import org.junit.Test; import rx.schedulers.Schedulers; import rx.schedulers.TestScheduler; import static com.netflix.titus.common.util.rx.batch.Priority.HIGH; import static com.netflix.titus.common.util.rx.batch.Priority.LOW; import static java.time.Duration.ofMillis; import static java.time.Duration.ofMinutes; import static java.time.Duration.ofSeconds; import static org.assertj.core.api.Assertions.assertThat; public class LargestPerTimeBucketTest { private static final long NO_BUCKETS = Long.MAX_VALUE; private TestScheduler testScheduler; @Before public void setUp() { testScheduler = Schedulers.test(); } @Test public void filterOutBatchesNotQueueingForAMinimumPeriod() { final Instant now = Instant.ofEpochMilli(testScheduler.now()); final Instant past = now.minus(ofMinutes(10)); final Stream<Batch<BatchableOperationMock, String>> batches = Stream.of( Batch.of("first", // only has recent items new BatchableOperationMock(LOW, now, "first", "sub1", "some"), new BatchableOperationMock(HIGH, now, "first", "sub2", "some"), new BatchableOperationMock(LOW, now, "first", "sub3", "some") ), Batch.of("second", new BatchableOperationMock(LOW, now, "second", "sub1", "some"), new BatchableOperationMock(LOW, now, "second", "sub2", "some"), new BatchableOperationMock(HIGH, past, "second", "sub3", "some") ), Batch.of("third", new BatchableOperationMock(LOW, past, "third", "sub1", "someState") ) ); EmissionStrategy strategy = new LargestPerTimeBucket(300_000 /* 5min */, NO_BUCKETS, testScheduler); Queue<Batch<BatchableOperationMock, String>> toEmit = strategy.compute(batches); // first was filtered out Assertions.assertThat(toEmit).hasSize(2); assertThat(toEmit.poll().getIndex()).isEqualTo("second"); assertThat(toEmit.poll().getIndex()).isEqualTo("third"); } @Test public void batchesWithOlderItemsGoFirst() { final long groupInBucketsOfMs = 1; final Instant now = Instant.ofEpochMilli(testScheduler.now()); final Stream<Batch<BatchableOperationMock, String>> batches = Stream.of( Batch.of("first", new BatchableOperationMock(LOW, now, "first", "sub1", "foo"), new BatchableOperationMock(LOW, now.minus(ofSeconds(1)), "first", "sub2", "foo") ), Batch.of("second", new BatchableOperationMock(HIGH, now.minus(ofSeconds(2)), "second", "sub1", "foo"), new BatchableOperationMock(LOW, now, "second", "sub2", "foo") ), Batch.of("third", new BatchableOperationMock(LOW, now.minus(ofMillis(2_001)), "third", "sub1", "foo"), new BatchableOperationMock(LOW, now, "third", "sub2", "foo") ), Batch.of("fourth", new BatchableOperationMock(LOW, now.minus(ofMinutes(1)), "fourth", "sub1", "foo"), new BatchableOperationMock(HIGH, now, "third", "sub2", "foo") ), Batch.of("fifth", new BatchableOperationMock(LOW, now.minus(ofMillis(1)), "fifth", "sub1", "foo"), new BatchableOperationMock(LOW, now, "third", "sub2", "foo") ) ); EmissionStrategy strategy = new LargestPerTimeBucket(0, groupInBucketsOfMs, testScheduler); Queue<Batch<BatchableOperationMock, String>> toEmit = strategy.compute(batches); Assertions.assertThat(toEmit).hasSize(5); assertThat(toEmit.poll().getIndex()).isEqualTo("fourth"); assertThat(toEmit.poll().getIndex()).isEqualTo("third"); assertThat(toEmit.poll().getIndex()).isEqualTo("second"); assertThat(toEmit.poll().getIndex()).isEqualTo("first"); assertThat(toEmit.poll().getIndex()).isEqualTo("fifth"); } @Test public void biggerBatchesInTheSameBucketGoFirst() { final long groupInBucketsOfMs = 60_000 /* 1min */; final Instant now = Instant.ofEpochMilli(testScheduler.now()); final Instant past = now.minus(ofMinutes(10)); final Stream<Batch<BatchableOperationMock, String>> batches = Stream.of( // 1-3 are in the same minute Batch.of("smaller", new BatchableOperationMock(LOW, now, "smaller", "sub1", "foo"), new BatchableOperationMock(LOW, past.minus(ofSeconds(10)), "smaller", "sub2", "foo") ), Batch.of("bigger", new BatchableOperationMock(LOW, past, "bigger", "sub1", "foo"), new BatchableOperationMock(HIGH, now.minus(ofMinutes(5)), "bigger", "sub2", "foo"), new BatchableOperationMock(LOW, now, "bigger", "sub3", "foo") ), Batch.of("slightlyOlder", new BatchableOperationMock(LOW, now, "slightlyOlder", "sub1", "foo"), new BatchableOperationMock(LOW, past.minus(ofSeconds(11)), "slightlyOlder", "sub2", "foo") ), Batch.of("older", new BatchableOperationMock(LOW, past.minus(ofMinutes(5)), "older", "sub1", "foo") ) ); EmissionStrategy strategy = new LargestPerTimeBucket(0, groupInBucketsOfMs, testScheduler); Queue<Batch<BatchableOperationMock, String>> toEmit = strategy.compute(batches); Assertions.assertThat(toEmit).hasSize(4); assertThat(toEmit.poll().getIndex()).isEqualTo("older"); // all following are in the same time bucket. Bigger go first, if same size, order by timestamp assertThat(toEmit.poll().getIndex()).isEqualTo("bigger"); assertThat(toEmit.poll().getIndex()).isEqualTo("slightlyOlder"); assertThat(toEmit.poll().getIndex()).isEqualTo("smaller"); } }
574
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/histogram/HistogramTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.histogram; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class HistogramTest { @Test public void testCorrectness() throws Exception { Histogram.Builder builder = Histogram.newBuilder(HistogramDescriptor.histogramOf(2, 5, 30, 60)); for (int i = 0; i <= 100; i++) { builder.increment(i); } Histogram histogram = builder.build(); assertThat(histogram.getCounters()).containsExactlyInAnyOrder(3L, 3L, 25L, 30L, 40L); } @Test(expected = IllegalArgumentException.class) public void testWrongBounds() throws Exception { HistogramDescriptor.histogramOf(1, 2, 0); } @Test(expected = IllegalArgumentException.class) public void testNoBounds() throws Exception { HistogramDescriptor.histogramOf(); } }
575
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/histogram/RollingCountTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.histogram; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class RollingCountTest { private static final long START_TIME = 1_000; private static final int STEPS = 4; private static final int STEP_TIME = 25; private final RollingCount rollingCount = RollingCount.rollingCount(STEP_TIME, STEPS, START_TIME); @Test public void testBasicProgression() { assertThat(rollingCount.getCounts(START_TIME)).isEqualTo(0); // Adds within the current window assertThat(rollingCount.addOne(START_TIME + 0 * STEP_TIME)).isEqualTo(1); assertThat(rollingCount.addOne(START_TIME + 1 * STEP_TIME)).isEqualTo(2); assertThat(rollingCount.addOne(START_TIME + 2 * STEP_TIME)).isEqualTo(3); assertThat(rollingCount.addOne(START_TIME + 3 * STEP_TIME)).isEqualTo(4); // Now passed the window assertThat(rollingCount.addOne(START_TIME + 4 * STEP_TIME)).isEqualTo(4); assertThat(rollingCount.addOne(START_TIME + 5 * STEP_TIME)).isEqualTo(4); assertThat(rollingCount.addOne(START_TIME + 7 * STEP_TIME)).isEqualTo(3); // Now get long into the future assertThat(rollingCount.getCounts(START_TIME + 1000 * STEP_TIME)).isEqualTo(0); } }
576
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/jackson/CommonObjectMappersTest.java
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.jackson; import java.util.Collections; import java.util.List; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import static com.netflix.titus.common.util.jackson.CommonObjectMappers.compactMapper; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; public class CommonObjectMappersTest { private final OuterClass NESTED_OBJECT = new OuterClass( "outerStringValue", 123, new InnerClass("innerStringValue", 321), asList(new InnerClass("item1", 1), new InnerClass("item2", 2)) ); @Test public void testFieldsFilter() throws Exception { OuterClass deserialized = filter(asList("stringValue", "objectValue.intValue", "objectValues.intValue")); assertThat(deserialized.stringValue).isEqualTo("outerStringValue"); assertThat(deserialized.intValue).isEqualTo(0); assertThat(deserialized.objectValue).isNotNull(); assertThat(deserialized.objectValue.stringValue).isNull(); assertThat(deserialized.objectValue.intValue).isEqualTo(321); assertThat(deserialized.objectValues).isNotNull(); } @Test public void testFieldsFilterWithFullInnerObjects() throws Exception { OuterClass deserialized = filter(Collections.singletonList("objectValue")); assertThat(deserialized.objectValue).isEqualTo(NESTED_OBJECT.objectValue); } @Test public void testFieldsFilterWithInvalidFieldDefinition() throws Exception { OuterClass deserialized = filter(Collections.singletonList("objectValue.intValue.fakeField")); assertThat(deserialized.objectValue.intValue).isEqualTo(0); } private OuterClass filter(List<String> fields) throws Exception { ObjectMapper mapper = CommonObjectMappers.applyFieldsFilter(compactMapper(), fields); String jsonValue = mapper.writeValueAsString(NESTED_OBJECT); return compactMapper().readValue(jsonValue, OuterClass.class); } private static class OuterClass { @JsonProperty private final String stringValue; @JsonProperty private final int intValue; @JsonProperty private final InnerClass objectValue; @JsonProperty private final List<InnerClass> objectValues; @JsonCreator private OuterClass(@JsonProperty("stringValue") String stringValue, @JsonProperty("intValue") int intValue, @JsonProperty("objectValue") InnerClass objectValue, @JsonProperty("objectValues") List<InnerClass> objectValues) { this.stringValue = stringValue; this.intValue = intValue; this.objectValue = objectValue; this.objectValues = objectValues; } } private static class InnerClass { @JsonProperty private final String stringValue; @JsonProperty private final int intValue; @JsonCreator private InnerClass(@JsonProperty("stringValue") String stringValue, @JsonProperty("intValue") int intValue) { this.stringValue = stringValue; this.intValue = intValue; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } InnerClass that = (InnerClass) o; if (intValue != that.intValue) { return false; } return stringValue != null ? stringValue.equals(that.stringValue) : that.stringValue == null; } @Override public String toString() { return "InnerClass{stringValue='" + stringValue + '\'' + ", intValue=" + intValue + '}'; } } }
577
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/jackson
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/jackson/internal/ProtobufMessageObjectMapperTest.java
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.jackson.internal; import java.util.Arrays; import java.util.List; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.deser.Deserializers; import com.fasterxml.jackson.databind.module.SimpleDeserializers; import com.google.protobuf.Message; import com.google.protobuf.util.JsonFormat; import com.netflix.titus.common.util.StringExt; import com.netflix.titus.grpc.protogen.Image; import org.assertj.core.api.Assertions; import org.junit.Test; public class ProtobufMessageObjectMapperTest { private static final String IMAGE_WRAPPER_JSON_STRING = "{\"image\":{\"name\":\"ubuntu\",\"tag\":\"latest\",\"digest\":\"\"}}"; @Test public void testMessageSerialization() throws Exception { Image image = getImage(); ObjectMapper objectMapper = getObjectMapper(); String jsonString = objectMapper.writeValueAsString(image); String expectedJsonString = JsonFormat.printer() .includingDefaultValueFields() .print(image); Assertions.assertThat(jsonString).isEqualTo(expectedJsonString); } @Test public void testMessageDeserialization() throws Exception { Image expectedImage = getImage(); String jsonString = JsonFormat.printer() .includingDefaultValueFields() .print(expectedImage); ObjectMapper objectMapper = getObjectMapper(); Image image = objectMapper.readValue(jsonString, Image.class); Assertions.assertThat(image).isEqualTo(expectedImage); } @Test public void testStringSerialization() throws Exception { String text = "TestString"; ObjectMapper objectMapper = getObjectMapper(); String jsonString = objectMapper.writeValueAsString(text); Assertions.assertThat(jsonString).isEqualTo(StringExt.doubleQuotes(text)); } @Test public void testStringDeserialization() throws Exception { String text = "TestString"; ObjectMapper objectMapper = getObjectMapper(); String jsonString = objectMapper.readValue(StringExt.doubleQuotes(text), String.class); Assertions.assertThat(jsonString).isEqualTo(text); } @Test public void testImageWrapperSerialization() throws Exception { ImageWrapper imageWrapper = new ImageWrapper(getImage()); ObjectMapper objectMapper = getObjectMapper(); String jsonString = objectMapper.writeValueAsString(imageWrapper) .replaceAll(" ", "") .replaceAll("\n", ""); Assertions.assertThat(jsonString).isEqualTo(IMAGE_WRAPPER_JSON_STRING); } @Test public void testImageWrapperDeserialization() throws Exception { ImageWrapper expectedImageWrapper = new ImageWrapper(getImage()); ObjectMapper objectMapper = getObjectMapper(); ImageWrapper imageWrapper = objectMapper.readValue(IMAGE_WRAPPER_JSON_STRING, ImageWrapper.class); Assertions.assertThat(imageWrapper).isEqualTo(expectedImageWrapper); } private ObjectMapper getObjectMapper() { ObjectMapper mapper = new ObjectMapper(); // Serialization mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); // Deserialization mapper.disable(SerializationFeature.INDENT_OUTPUT); SimpleDeserializers simpleDeserializers = new SimpleDeserializers(); simpleDeserializers.addDeserializer(String.class, new TrimmingStringDeserializer()); List<Deserializers> deserializersList = Arrays.asList( new AssignableFromDeserializers(Message.class, new ProtobufMessageDeserializer()), simpleDeserializers ); CompositeDeserializers compositeDeserializers = new CompositeDeserializers(deserializersList); CustomDeserializerSimpleModule module = new CustomDeserializerSimpleModule(compositeDeserializers); module.addSerializer(Message.class, new ProtobufMessageSerializer()); mapper.registerModule(module); return mapper; } private Image getImage() { return Image.newBuilder() .setName("ubuntu") .setTag("latest") .build(); } private static class ImageWrapper { private final Image image; @JsonCreator ImageWrapper(@JsonProperty("image") Image image) { this.image = image; } public Image getImage() { return image; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ImageWrapper that = (ImageWrapper) o; return Objects.equals(image, that.image); } @Override public int hashCode() { return image != null ? image.hashCode() : 0; } } }
578
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/framework/fit
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/framework/fit/internal/FitInvocationHandlerTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.fit.internal; import java.util.concurrent.Callable; import java.util.concurrent.CompletableFuture; import com.google.common.collect.ImmutableMap; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.netflix.titus.common.framework.fit.FitFramework; import com.netflix.titus.common.framework.fit.FitInjection; import com.netflix.titus.common.framework.fit.internal.action.FitErrorAction; import org.junit.Before; import org.junit.Test; import rx.Observable; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; public class FitInvocationHandlerTest { private final FitFramework fitFramework = FitFramework.newFitFramework(); private final FitInjection fitInjection = fitFramework.newFitInjectionBuilder("testInjection") .withExceptionType(MyException.class) .build(); private final MyApiImpl myApiImpl = new MyApiImpl(); private final MyApi myApi = fitFramework.newFitProxy(myApiImpl, fitInjection); @Before public void setUp() { fitFramework.getRootComponent().addInjection(fitInjection); } @Test public void testBeforeSynchronous() { configureAction(true); try { myApi.runSynchronous("hello"); fail("Expected FIT injected error"); } catch (MyException e) { assertThat(myApiImpl.getExecutionCounter()).isEqualTo(0); } assertThat(myApi.runSynchronous("hello")).isEqualTo("hello"); } @Test public void testAfterSynchronous() { configureAction(false); try { myApi.runSynchronous("hello"); fail("Expected FIT injected error"); } catch (MyException e) { assertThat(myApiImpl.getExecutionCounter()).isEqualTo(1); } assertThat(myApi.runSynchronous("hello")).isEqualTo("hello"); } @Test public void testBeforeCompletableFuture() throws Exception { runBefore(true, () -> myApi.runCompletableFuture("hello").get(), 0); } @Test public void testAfterCompletableFuture() throws Exception { runBefore(false, () -> myApi.runCompletableFuture("hello").get(), 1); } @Test public void testBeforeListenableFuture() throws Exception { runBefore(true, () -> myApi.runListenableFuture("hello").get(), 0); } @Test public void testAfterListenableFuture() throws Exception { runBefore(false, () -> myApi.runListenableFuture("hello").get(), 1); } private void runBefore(boolean before, Callable<String> action, int executionCount) throws Exception { configureAction(before); try { action.call(); fail("Expected FIT injected error"); } catch (Exception e) { assertThat(e.getCause()).isInstanceOf(MyException.class); assertThat(myApiImpl.getExecutionCounter()).isEqualTo(executionCount); } assertThat(action.call()).isEqualTo("hello"); } @Test public void testBeforeObservable() { configureAction(true); try { myApi.runObservable("hello").toBlocking().last(); fail("Expected FIT injected error"); } catch (MyException e) { assertThat(myApiImpl.getExecutionCounter()).isEqualTo(0); } assertThat(myApi.runObservable("hello").toBlocking().first()).isEqualTo("hello"); } @Test public void testAfterObservable() { configureAction(false); try { myApi.runObservable("hello").toBlocking().last(); fail("Expected FIT injected error"); } catch (MyException e) { assertThat(myApiImpl.getExecutionCounter()).isEqualTo(1); } assertThat(myApi.runObservable("hello").toBlocking().first()).isEqualTo("hello"); } private void configureAction(boolean before) { fitInjection.addAction(new FitErrorAction("errorAction", ImmutableMap.of( "percentage", "20", "before", Boolean.toString(before), "errorTime", "1m", "upTime", "0s" ), fitInjection)); } public static class MyException extends RuntimeException { public MyException(String message) { super(message); } } public interface MyApi { String runSynchronous(String hello); CompletableFuture<String> runCompletableFuture(String arg); ListenableFuture<String> runListenableFuture(String arg); Observable<String> runObservable(String arg); } public static class MyApiImpl implements MyApi { private volatile int executionCounter; public int getExecutionCounter() { return executionCounter; } @Override public String runSynchronous(String arg) { executionCounter++; return arg; } @Override public ListenableFuture<String> runListenableFuture(String arg) { executionCounter++; return Futures.immediateFuture(arg); } @Override public CompletableFuture<String> runCompletableFuture(String arg) { executionCounter++; return CompletableFuture.completedFuture(arg); } @Override public Observable<String> runObservable(String arg) { return Observable.fromCallable(() -> { executionCounter++; return arg; }); } } }
579
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/framework/scheduler
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/framework/scheduler/internal/LocalSchedulerTransactionLoggerTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.scheduler.internal; import java.time.Duration; import java.util.Collections; import com.netflix.titus.common.framework.scheduler.model.Schedule; import com.netflix.titus.common.framework.scheduler.model.ScheduleDescriptor; import com.netflix.titus.common.framework.scheduler.model.ScheduledAction; import com.netflix.titus.common.framework.scheduler.model.SchedulingStatus; import com.netflix.titus.common.framework.scheduler.model.SchedulingStatus.SchedulingState; import com.netflix.titus.common.framework.scheduler.model.ExecutionId; import com.netflix.titus.common.framework.scheduler.model.event.ScheduleAddedEvent; import com.netflix.titus.common.framework.scheduler.model.event.ScheduleRemovedEvent; import com.netflix.titus.common.framework.scheduler.model.event.ScheduleUpdateEvent; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.assertj.core.api.Assertions.assertThat; /** * Sole purpose of this test is visual inspection of the generated log line. */ public class LocalSchedulerTransactionLoggerTest { private static final Logger logger = LoggerFactory.getLogger(LocalSchedulerTransactionLoggerTest.class); private static final Schedule REFERENCE_SCHEDULE = Schedule.newBuilder() .withId("reference") .withDescriptor(ScheduleDescriptor.newBuilder() .withName("testSchedule") .withDescription("Testing...") .withTimeout(Duration.ofSeconds(1)) .withInterval(Duration.ofSeconds(5)) .build() ) .withCurrentAction(ScheduledAction.newBuilder() .withId("reference") .withStatus(newSchedulingStatus(SchedulingState.Waiting)) .withIteration(ExecutionId.initial()) .build() ) .build(); @Test public void testDoFormatScheduleAdded() { verify(LocalSchedulerTransactionLogger.doFormat(new ScheduleAddedEvent(REFERENCE_SCHEDULE))); } @Test public void testDoFormatScheduleRemoved() { verify(LocalSchedulerTransactionLogger.doFormat(new ScheduleRemovedEvent(REFERENCE_SCHEDULE))); } @Test public void testDoFormatScheduleRunningUpdate() { Schedule schedule = updateStatus(REFERENCE_SCHEDULE, newSchedulingStatus(SchedulingState.Running)); verify(LocalSchedulerTransactionLogger.doFormat(new ScheduleUpdateEvent(schedule))); } @Test public void testDoFormatScheduleSuccessUpdate() { Schedule schedule = updateStatus(REFERENCE_SCHEDULE, newSchedulingStatus(SchedulingState.Succeeded)); verify(LocalSchedulerTransactionLogger.doFormat(new ScheduleUpdateEvent(schedule))); } @Test public void testDoFormatScheduleFailureUpdate() { Schedule schedule = updateStatus(REFERENCE_SCHEDULE, newSchedulingStatus(SchedulingState.Failed)); verify(LocalSchedulerTransactionLogger.doFormat(new ScheduleUpdateEvent(schedule))); } @Test public void testDoFormatNewAction() { Schedule firstCompleted = updateStatus(REFERENCE_SCHEDULE, newSchedulingStatus(SchedulingState.Succeeded)); Schedule nextAction = firstCompleted.toBuilder() .withCurrentAction(ScheduledAction.newBuilder() .withId("reference") .withStatus(newSchedulingStatus(SchedulingState.Waiting)) .withIteration(ExecutionId.initial()) .build() ) .withCompletedActions(Collections.singletonList(firstCompleted.getCurrentAction())) .build(); verify(LocalSchedulerTransactionLogger.doFormat(new ScheduleUpdateEvent(nextAction))); } private void verify(String logEntry) { assertThat(logEntry).isNotEmpty(); logger.info("Transaction log entry: {}", logEntry); } private static SchedulingStatus newSchedulingStatus(SchedulingState schedulingState) { return SchedulingStatus.newBuilder() .withState(schedulingState) .withTimestamp(System.currentTimeMillis()) .withExpectedStartTime(schedulingState == SchedulingState.Waiting ? System.currentTimeMillis() + 1_000 : 0) .withError(schedulingState == SchedulingState.Failed ? new RuntimeException("Simulated error") : null) .build(); } private Schedule updateStatus(Schedule schedule, SchedulingStatus newStatus) { return schedule.toBuilder() .withCurrentAction(schedule.getCurrentAction().toBuilder() .withStatus(newStatus) .withStatusHistory(Collections.singletonList(schedule.getCurrentAction().getStatus())) .build() ) .build(); } }
580
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/framework/scheduler
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/framework/scheduler/internal/DefaultLocalSchedulerPerf.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.scheduler.internal; import java.time.Duration; import java.util.HashSet; import java.util.Set; import java.util.concurrent.atomic.AtomicLong; import com.netflix.spectator.api.DefaultRegistry; import com.netflix.titus.common.framework.scheduler.ExecutionContext; import com.netflix.titus.common.framework.scheduler.LocalScheduler; import com.netflix.titus.common.framework.scheduler.ScheduleReference; import com.netflix.titus.common.framework.scheduler.model.ScheduleDescriptor; import com.netflix.titus.common.framework.scheduler.model.ScheduledAction; import com.netflix.titus.common.framework.scheduler.model.SchedulingStatus; import com.netflix.titus.common.framework.scheduler.model.event.ScheduleRemovedEvent; import com.netflix.titus.common.framework.scheduler.model.event.ScheduleUpdateEvent; import com.netflix.titus.common.util.time.Clocks; import reactor.core.publisher.Mono; import reactor.core.scheduler.Schedulers; public class DefaultLocalSchedulerPerf { private static final Duration LOOP_INTERVAL = Duration.ofMillis(10); private static final int EXECUTIONS = 10; private static final long ACTIVE_SCHEDULE_COUNT = 10; private final LocalScheduler localScheduler = new DefaultLocalScheduler(LOOP_INTERVAL, Schedulers.parallel(), Clocks.system(), new DefaultRegistry()); private final Set<ScheduleReference> activeReferences = new HashSet<>(); private final AtomicLong successes = new AtomicLong(); private final AtomicLong expectedFailures = new AtomicLong(); private final AtomicLong removedEvents = new AtomicLong(); private final AtomicLong tooFastSchedules = new AtomicLong(); private final AtomicLong delayedSchedules = new AtomicLong(); private final AtomicLong eventFailures = new AtomicLong(); private void doRun() throws InterruptedException { long lastUpdateTimestamp = 0; while (true) { if (lastUpdateTimestamp + 1000 < System.currentTimeMillis()) { printReport(); lastUpdateTimestamp = System.currentTimeMillis(); } while (activeReferences.size() < ACTIVE_SCHEDULE_COUNT) { activeReferences.add(newMonoAction(false)); activeReferences.add(newMonoAction(true)); activeReferences.add(newAction(false)); activeReferences.add(newAction(true)); } activeReferences.removeIf(ScheduleReference::isClosed); Thread.sleep(10); } } private void printReport() { System.out.println(String.format("active=%8s, finished=%8s, successes=%8s, expectedFailures=%8s, failureEvents=%8s, removedEvents=%8s, tooFastSchedules=%8s, delayedSchedules=%8s", activeReferences.size(), localScheduler.getArchivedSchedules().size(), successes.get(), expectedFailures.get(), eventFailures.get(), removedEvents.get(), tooFastSchedules.get(), delayedSchedules.get() )); } private ScheduleReference newMonoAction(boolean failSometimes) { int intervalMs = 50; ScheduleReference reference = localScheduler.scheduleMono( ScheduleDescriptor.newBuilder() .withName("monoAction") .withDescription("Test...") .withInterval(Duration.ofMillis(intervalMs)) .withTimeout(Duration.ofSeconds(1)) .build(), context -> { checkSchedulingLatency(intervalMs, context); if (context.getExecutionId().getTotal() > EXECUTIONS) { localScheduler.cancel(context.getId()).subscribe(); return Mono.empty(); } if (failSometimes && context.getExecutionId().getTotal() % 2 == 0) { expectedFailures.incrementAndGet(); return Mono.error(new RuntimeException("Simulated error")); } return Mono.delay(Duration.ofMillis(10)).ignoreElement() .cast(Void.class) .doOnError(Throwable::printStackTrace) .doOnSuccess(next -> successes.incrementAndGet()); }, Schedulers.parallel() ); observeEvents(reference); return reference; } private ScheduleReference newAction(boolean failSometimes) { int intervalMs = 50; ScheduleReference reference = localScheduler.schedule( ScheduleDescriptor.newBuilder() .withName("runnableAction") .withDescription("Test...") .withInterval(Duration.ofMillis(intervalMs)) .withTimeout(Duration.ofSeconds(1)) .build(), context -> { checkSchedulingLatency(intervalMs, context); if (context.getExecutionId().getTotal() > EXECUTIONS) { localScheduler.cancel(context.getId()).subscribe(); return; } if (failSometimes && context.getExecutionId().getTotal() % 2 == 0) { expectedFailures.incrementAndGet(); throw new RuntimeException("Simulated error"); } try { Thread.sleep(10); successes.incrementAndGet(); } catch (InterruptedException ignore) { } }, true ); observeEvents(reference); return reference; } private void checkSchedulingLatency(int intervalMs, ExecutionContext context) { if (context.getPreviousAction().isPresent()) { ScheduledAction previous = context.getPreviousAction().get(); long actualDelayMs = System.currentTimeMillis() - previous.getStatus().getTimestamp(); if (actualDelayMs < intervalMs) { tooFastSchedules.incrementAndGet(); } if (actualDelayMs > 2 * intervalMs) { delayedSchedules.incrementAndGet(); } } } private void observeEvents(ScheduleReference reference) { localScheduler.events() .filter(e -> e.getSchedule().getId().equals(reference.getSchedule().getId())) .subscribe(event -> { if (event instanceof ScheduleUpdateEvent) { ScheduleUpdateEvent updateEvent = (ScheduleUpdateEvent) event; ScheduledAction action = updateEvent.getSchedule().getCurrentAction(); if (action.getStatus().getState() == SchedulingStatus.SchedulingState.Failed) { eventFailures.incrementAndGet(); } } else if (event instanceof ScheduleRemovedEvent) { removedEvents.incrementAndGet(); } }); } public static void main(String[] args) throws InterruptedException { new DefaultLocalSchedulerPerf().doRun(); } }
581
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/framework/scheduler
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/framework/scheduler/internal/DefaultLocalSchedulerTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.scheduler.internal; import java.time.Duration; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import com.netflix.spectator.api.DefaultRegistry; import com.netflix.titus.common.framework.scheduler.LocalScheduler; import com.netflix.titus.common.framework.scheduler.ScheduleReference; import com.netflix.titus.common.framework.scheduler.model.Schedule; import com.netflix.titus.common.framework.scheduler.model.ScheduleDescriptor; import com.netflix.titus.common.framework.scheduler.model.ScheduledAction; import com.netflix.titus.common.framework.scheduler.model.SchedulingStatus.SchedulingState; import com.netflix.titus.common.framework.scheduler.model.event.LocalSchedulerEvent; import com.netflix.titus.common.framework.scheduler.model.event.ScheduleAddedEvent; import com.netflix.titus.common.framework.scheduler.model.event.ScheduleRemovedEvent; import com.netflix.titus.common.framework.scheduler.model.event.ScheduleUpdateEvent; import com.netflix.titus.common.util.retry.Retryers; import com.netflix.titus.common.util.time.Clocks; import com.netflix.titus.testkit.rx.TitusRxSubscriber; import org.junit.Before; import org.junit.Test; import reactor.core.publisher.Mono; import reactor.core.scheduler.Schedulers; import static com.jayway.awaitility.Awaitility.await; import static org.assertj.core.api.Assertions.assertThat; public class DefaultLocalSchedulerTest { private final AtomicReference<ScheduledAction> lastSucceededAction = new AtomicReference<>(); private final AtomicReference<ScheduledAction> lastFailedAction = new AtomicReference<>(); private final ScheduleDescriptor scheduleDescriptor = ScheduleDescriptor.newBuilder() .withName("testSchedule") .withDescription("Test scheduler") .withInterval(Duration.ofMillis(1)) .withTimeout(Duration.ofMillis(500)) .withRetryerSupplier(() -> Retryers.interval(100, TimeUnit.MILLISECONDS)) .withOnSuccessHandler(lastSucceededAction::set) .withOnErrorHandler((action, error) -> lastFailedAction.set(action)) .build(); private final LocalScheduler localScheduler = new DefaultLocalScheduler(Duration.ofMillis(1), Schedulers.parallel(), Clocks.system(), new DefaultRegistry()); private final TitusRxSubscriber<LocalSchedulerEvent> eventSubscriber = new TitusRxSubscriber<>(); @Before public void setUp() { localScheduler.events().subscribe(eventSubscriber); } @Test(timeout = 60_000) public void testScheduleMono() throws Exception { AtomicLong tickCounter = new AtomicLong(); ScheduleReference reference = localScheduler.scheduleMono( scheduleDescriptor.toBuilder().withName("testScheduleMono").build(), tick -> Mono.delay(Duration.ofMillis(1)).flatMap(t -> { tickCounter.incrementAndGet(); return Mono.empty(); }), Schedulers.parallel() ); testExecutionLifecycle(reference, tickCounter); } @Test(timeout = 60_000) public void testScheduleAction() throws Exception { AtomicLong tickCounter = new AtomicLong(); ScheduleReference reference = localScheduler.schedule( scheduleDescriptor.toBuilder().withName("testScheduleAction").build(), t -> tickCounter.incrementAndGet(), true ); testExecutionLifecycle(reference, tickCounter); } private void testExecutionLifecycle(ScheduleReference reference, AtomicLong tickCounter) throws InterruptedException { // Schedule, and first iteration expectScheduleAdded(reference); expectScheduleUpdateEvent(SchedulingState.Running); expectScheduleUpdateEvent(SchedulingState.Succeeded); assertThat(tickCounter.get()).isGreaterThan(0); // Next running expectScheduleUpdateEvent(SchedulingState.Waiting); expectScheduleUpdateEvent(SchedulingState.Running); ScheduleUpdateEvent succeededEvent2 = expectScheduleUpdateEvent(SchedulingState.Succeeded); assertThat(succeededEvent2.getSchedule().getCompletedActions()).hasSize(1); // Now cancel it assertThat(reference.isClosed()).isFalse(); reference.cancel(); await().atMost(30, TimeUnit.SECONDS).until(reference::isClosed); assertThat(reference.getSchedule().getCurrentAction().getStatus().getState().isFinal()).isTrue(); assertThat(localScheduler.getActiveSchedules()).isEmpty(); assertThat(localScheduler.getArchivedSchedules()).hasSize(1); expectScheduleRemoved(reference); } @Test public void testTimeout() throws Exception { ScheduleReference reference = localScheduler.scheduleMono( scheduleDescriptor.toBuilder().withName("testTimeout").build(), tick -> Mono.never(), Schedulers.parallel() ); expectScheduleAdded(reference); expectScheduleUpdateEvent(SchedulingState.Running); expectScheduleUpdateEvent(SchedulingState.Failed); // Replacement expectScheduleUpdateEvent(SchedulingState.Waiting); assertThat(reference.getSchedule().getCompletedActions()).hasSize(1); ScheduledAction failedAction = reference.getSchedule().getCompletedActions().get(0); assertThat(failedAction.getStatus().getState()).isEqualTo(SchedulingState.Failed); assertThat(failedAction.getStatus().getError().get()).isInstanceOf(TimeoutException.class); } @Test public void testRetries() throws InterruptedException { AtomicInteger counter = new AtomicInteger(); ScheduleReference reference = localScheduler.scheduleMono( scheduleDescriptor.toBuilder().withName("testRetries").build(), tick -> Mono.defer(() -> counter.incrementAndGet() % 2 == 0 ? Mono.empty() : Mono.error(new RuntimeException("Simulated error at iteration " + counter.get()))), Schedulers.parallel() ); expectScheduleAdded(reference); expectScheduleUpdateEvent(SchedulingState.Running); expectScheduleUpdateEvent(SchedulingState.Failed); expectScheduleUpdateEvent(SchedulingState.Waiting); expectScheduleUpdateEvent(SchedulingState.Running); expectScheduleUpdateEvent(SchedulingState.Succeeded); } private void expectScheduleAdded(ScheduleReference reference) throws InterruptedException { assertThat(reference.isClosed()).isFalse(); LocalSchedulerEvent addedEvent = eventSubscriber.takeNext(Duration.ofSeconds(5)); assertThat(addedEvent).isInstanceOf(ScheduleAddedEvent.class); assertThat(addedEvent.getSchedule().getCurrentAction().getStatus().getState()).isEqualTo(SchedulingState.Waiting); assertThat(localScheduler.findSchedule(reference.getSchedule().getId())).isPresent(); } private void expectScheduleRemoved(ScheduleReference reference) throws InterruptedException { assertThat(reference.isClosed()).isTrue(); LocalSchedulerEvent removedEvent = eventSubscriber.takeUntil(e -> e instanceof ScheduleRemovedEvent, Duration.ofSeconds(5)); Schedule schedule = removedEvent.getSchedule(); assertThat(schedule.getCurrentAction().getStatus().getState().isFinal()).isTrue(); assertThat(localScheduler.getArchivedSchedules()).hasSize(1); assertThat(localScheduler.getArchivedSchedules().get(0).getId()).isEqualTo(reference.getSchedule().getId()); } private ScheduleUpdateEvent expectScheduleUpdateEvent(SchedulingState expectedState) throws InterruptedException { LocalSchedulerEvent event = eventSubscriber.takeNext(Duration.ofSeconds(5)); assertThat(event).isInstanceOf(ScheduleUpdateEvent.class); assertThat(event.getSchedule().getCurrentAction().getStatus().getState()).isEqualTo(expectedState); return (ScheduleUpdateEvent) event; } }
582
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/framework/simplereconciler
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/framework/simplereconciler/internal/DefaultOneOffReconcilerTest.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.simplereconciler.internal; import java.time.Duration; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; import com.netflix.titus.common.framework.simplereconciler.ReconcilerActionProvider; import com.netflix.titus.common.framework.simplereconciler.ReconcilerActionProviderPolicy; import com.netflix.titus.common.framework.simplereconciler.internal.provider.ActionProviderSelectorFactory; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.runtime.TitusRuntimes; import com.netflix.titus.common.util.Evaluators; import com.netflix.titus.common.util.rx.ReactorExt; import com.netflix.titus.testkit.rx.TitusRxSubscriber; import org.junit.After; import org.junit.Test; import reactor.core.Disposable; import reactor.core.publisher.Mono; import reactor.core.scheduler.Schedulers; import static com.jayway.awaitility.Awaitility.await; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; public class DefaultOneOffReconcilerTest { private static final Duration QUICK_CYCLE = Duration.ofMillis(1); private static final Duration LONG_CYCLE = Duration.ofMillis(2); private static final Duration TIMEOUT = Duration.ofSeconds(30); private static final String INITIAL = "initial"; private static final String RECONCILED = "Reconciled"; private final TitusRuntime titusRuntime = TitusRuntimes.internal(); private DefaultOneOffReconciler<String> reconciler; private TitusRxSubscriber<String> changesSubscriber; @After public void tearDown() { ReactorExt.safeDispose(changesSubscriber); Evaluators.acceptNotNull(reconciler, r -> r.close().block(TIMEOUT)); } @Test(timeout = 30_000) public void testExternalAction() { newReconciler(current -> Collections.emptyList()); assertThat(reconciler.apply(c -> Mono.just("update")).block()).isEqualTo("update"); assertThat(changesSubscriber.takeNext()).isEqualTo("update"); assertThat(changesSubscriber.takeNext()).isNull(); } @Test(timeout = 30_000) public void testExternalActionCancel() throws Exception { newReconciler(current -> Collections.emptyList()); CountDownLatch latch = new CountDownLatch(1); AtomicBoolean canceled = new AtomicBoolean(); Mono<String> action = Mono.<String>never() .doOnSubscribe(s -> latch.countDown()) .doOnCancel(() -> canceled.set(true)); Disposable disposable = reconciler.apply(c -> action).subscribe(); latch.await(); assertThat(disposable.isDisposed()).isFalse(); assertThat(canceled.get()).isFalse(); disposable.dispose(); await().until(canceled::get); assertThat(changesSubscriber.takeNext()).isNull(); // Now run regular action assertThat(reconciler.apply(anything -> Mono.just("Regular")).block(TIMEOUT)).isEqualTo("Regular"); } @Test(timeout = 30_000) public void testExternalActionMonoError() { newReconciler(current -> Collections.emptyList()); try { reconciler.apply(anything -> Mono.error(new RuntimeException("simulated error"))).block(); fail("Expected error"); } catch (Exception e) { assertThat(e).isInstanceOf(RuntimeException.class); assertThat(e.getMessage()).isEqualTo("simulated error"); } assertThat(changesSubscriber.takeNext()).isNull(); } @Test(timeout = 30_000) public void testExternalActionFunctionError() { newReconciler(current -> Collections.emptyList()); try { reconciler.apply(c -> { throw new RuntimeException("simulated error"); }).block(); fail("Expected error"); } catch (Exception e) { assertThat(e).isInstanceOf(RuntimeException.class); assertThat(e.getMessage()).isEqualTo("simulated error"); } assertThat(changesSubscriber.takeNext()).isNull(); } @Test(timeout = 30_000) public void testReconcilerAction() throws InterruptedException { AtomicInteger idx = new AtomicInteger(); newReconciler(current -> Collections.singletonList(Mono.just(v -> RECONCILED + idx.getAndIncrement()))); String expected = RECONCILED + (idx.get() + 1); assertThat(changesSubscriber.takeUntil(expected::equals, TIMEOUT)).isNotNull(); } @Test(timeout = 30_000) public void testReconcilerActionMonoError() throws InterruptedException { AtomicBoolean failedRef = new AtomicBoolean(); newReconciler(current -> Collections.singletonList(failedRef.getAndSet(true) ? Mono.just(v -> RECONCILED) : Mono.error(new RuntimeException("simulated error")) )); assertThat(changesSubscriber.takeNext(TIMEOUT)).isEqualTo(RECONCILED); } @Test(timeout = 30_000) public void testReconcilerActionFunctionError() throws InterruptedException { AtomicBoolean failedRef = new AtomicBoolean(); newReconciler(current -> Collections.singletonList(Mono.just(v -> { if (failedRef.getAndSet(true)) { return RECONCILED; } throw new RuntimeException("simulated error"); }))); assertThat(changesSubscriber.takeNext(TIMEOUT)).isEqualTo(RECONCILED); } @Test(timeout = 30_000) public void testReconcilerCloseWithRunningExternalAction() { newReconciler(current -> Collections.emptyList()); TitusRxSubscriber<String> subscriber1 = new TitusRxSubscriber<>(); TitusRxSubscriber<String> subscriber2 = new TitusRxSubscriber<>(); reconciler.apply(c -> Mono.never()).subscribe(subscriber1); reconciler.apply(c -> Mono.never()).subscribe(subscriber2); assertThat(subscriber1.isOpen()).isTrue(); assertThat(subscriber2.isOpen()).isTrue(); reconciler.close().subscribe(); await().until(() -> !subscriber1.isOpen()); await().until(() -> !subscriber2.isOpen()); assertThat(subscriber1.getError().getMessage()).isEqualTo("cancelled"); assertThat(subscriber2.getError().getMessage()).isEqualTo("cancelled"); await().until(() -> !changesSubscriber.isOpen()); } @Test(timeout = 30_000) public void testReconcilerCloseWithRunningReconciliationAction() throws InterruptedException { // Start reconciliation action first CountDownLatch ready = new CountDownLatch(1); AtomicBoolean cancelled = new AtomicBoolean(); Mono<Function<String, String>> action = Mono.<Function<String, String>>never() .doOnSubscribe(s -> ready.countDown()) .doOnCancel(() -> cancelled.set(true)); newReconciler(current -> Collections.singletonList(action)); ready.await(); TitusRxSubscriber<String> subscriber = new TitusRxSubscriber<>(); reconciler.apply(c -> Mono.never()).subscribe(subscriber); assertThat(subscriber.isOpen()).isTrue(); reconciler.close().subscribe(); await().until(() -> cancelled.get() && !subscriber.isOpen()); assertThat(subscriber.getError().getMessage()).isEqualTo("cancelled"); await().until(() -> !changesSubscriber.isOpen()); } private void newReconciler(Function<String, List<Mono<Function<String, String>>>> reconcilerActionsProvider) { ActionProviderSelectorFactory<String> selectorFactory = new ActionProviderSelectorFactory<>("test", Arrays.asList( new ReconcilerActionProvider<>(ReconcilerActionProviderPolicy.getDefaultExternalPolicy(), true, data -> Collections.emptyList()), new ReconcilerActionProvider<>(ReconcilerActionProviderPolicy.getDefaultInternalPolicy(), false, reconcilerActionsProvider) ), titusRuntime); this.reconciler = new DefaultOneOffReconciler<>( "junit", INITIAL, QUICK_CYCLE, LONG_CYCLE, selectorFactory, Schedulers.parallel(), titusRuntime ); this.changesSubscriber = new TitusRxSubscriber<>(); reconciler.changes().subscribe(changesSubscriber); String event = changesSubscriber.takeNext(); if (!event.equals(INITIAL) && !event.startsWith(RECONCILED)) { fail("Unexpected event: " + event); } } }
583
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/framework/simplereconciler
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/framework/simplereconciler/internal/DefaultManyReconcilerPerf.java
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.simplereconciler.internal; import java.time.Duration; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Function; import com.google.common.base.Stopwatch; import com.netflix.titus.common.framework.simplereconciler.ManyReconciler; import com.netflix.titus.common.framework.simplereconciler.ReconcilerActionProviderPolicy; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.runtime.TitusRuntimes; import reactor.core.Disposable; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; public class DefaultManyReconcilerPerf { private static final int SHARD_COUNT = 10; private static final int ENGINE_COUNT = 2000; private static final int LIMIT = 10; private final TitusRuntime titusRuntime = TitusRuntimes.internal(); private final ManyReconciler<Integer> reconciler; private final AtomicBoolean initialized = new AtomicBoolean(); private Disposable eventSubscription; public DefaultManyReconcilerPerf() { ReconcilerActionProviderPolicy internalProviderPolicy = ReconcilerActionProviderPolicy.newBuilder() .withName("slow") .withPriority(ReconcilerActionProviderPolicy.DEFAULT_INTERNAL_ACTIONS_PRIORITY) .build(); Function<Integer, List<Mono<Function<Integer, Integer>>>> internalActionsProvider = data -> { if (!initialized.get()) { return Collections.emptyList(); } long delayMs = Math.max(1, System.nanoTime() % 10); try { Thread.sleep(1); } catch (InterruptedException ignore) { } return Collections.singletonList(Mono.just(current -> current + 1)); }; this.reconciler = ManyReconciler.<Integer>newBuilder() .withName("test") .withShardCount(SHARD_COUNT) .withQuickCycle(Duration.ofMillis(1)) .withLongCycle(Duration.ofMillis(1)) .withExternalActionProviderPolicy(ReconcilerActionProviderPolicy.getDefaultExternalPolicy()) .withReconcilerActionsProvider(internalProviderPolicy, internalActionsProvider) .withTitusRuntime(titusRuntime) .build(); } private void load(int engineCount) { Stopwatch stopwatch = Stopwatch.createStarted(); List<Mono<Void>> action = new ArrayList<>(); for (int i = 0; i < engineCount; i++) { action.add(reconciler.add("#" + i, i)); } Flux.merge(action).collectList().block(); System.out.println("Created jobs in " + stopwatch.elapsed(TimeUnit.MILLISECONDS) + "ms"); initialized.set(true); } private void run(int limit) { Stopwatch stopwatch = Stopwatch.createStarted(); this.eventSubscription = reconciler.changes().subscribe( events -> { // events.forEach(event -> { // System.out.println("EngineId=" + event.getId() + ", DataVersion=" + event.getData()); // }); } ); System.out.println("Engines to watch: " + reconciler.getAll().size()); while (!haveAllEnginesReachedLimit(limit)) { try { Thread.sleep(100); } catch (InterruptedException ignore) { } } System.out.println("All engines reached limit " + limit + " in " + stopwatch.elapsed(TimeUnit.MILLISECONDS) + "ms"); } private void stop() { eventSubscription.dispose(); reconciler.close().block(); } private boolean haveAllEnginesReachedLimit(int limit) { for (int counter : reconciler.getAll().values()) { if (counter < limit) { return false; } } return true; } public static void main(String[] args) { DefaultManyReconcilerPerf perf = new DefaultManyReconcilerPerf(); perf.load(ENGINE_COUNT); perf.run(LIMIT); perf.stop(); } }
584
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/framework/simplereconciler
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/framework/simplereconciler/internal/ShardedManyReconcilerTest.java
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.simplereconciler.internal; import java.util.Iterator; import java.util.List; import com.google.common.base.Preconditions; import com.netflix.titus.common.framework.simplereconciler.SimpleReconcilerEvent; import com.netflix.titus.common.util.closeable.CloseableReference; import com.netflix.titus.common.util.collections.index.IndexSetHolderConcurrent; import com.netflix.titus.common.util.collections.index.Indexes; import org.junit.After; import org.junit.Test; import reactor.core.publisher.Mono; import reactor.core.scheduler.Scheduler; import reactor.core.scheduler.Schedulers; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; public class ShardedManyReconcilerTest { private final StubManyReconciler<String> shard1 = new StubManyReconciler<>(); private final StubManyReconciler<String> shard2 = new StubManyReconciler<>(); private final CloseableReference<Scheduler> notificationSchedulerRef = CloseableReference.referenceOf( Schedulers.newSingle("reconciler-notification-junit", true), Scheduler::dispose ); private final ShardedManyReconciler<String> reconciler = new ShardedManyReconciler<>( 2, id -> id.contains("shard1") ? 0 : 1, shardIdx -> { Preconditions.checkArgument(shardIdx < 2); return shardIdx == 0 ? shard1 : shard2; }, notificationSchedulerRef, new IndexSetHolderConcurrent<>(Indexes.empty()) ); @After public void tearDown() throws Exception { reconciler.close().block(); } @Test(timeout = 30_000) public void testAdd() { Iterator<List<SimpleReconcilerEvent<String>>> eventsIt = reconciler.changes("junit").toIterable().iterator(); assertThat(eventsIt.hasNext()).isTrue(); assertThat(eventsIt.next()).isEmpty(); // Shard1 reconciler.add("abc_shard1", "value1").block(); expectEvent(eventsIt, SimpleReconcilerEvent.Kind.Added, "abc_shard1", "value1"); assertThat(shard1.findById("abc_shard1")).isNotNull(); assertThat(shard2.getAll()).isEmpty(); // Shard2 reconciler.add("abc_shard2", "value2").block(); expectEvent(eventsIt, SimpleReconcilerEvent.Kind.Added, "abc_shard2", "value2"); assertThat(shard1.getAll()).hasSize(1); assertThat(shard2.findById("abc_shard1")).isNotNull(); } @Test(timeout = 30_000) public void testApplyChange() { Iterator<List<SimpleReconcilerEvent<String>>> eventIt = addData("1@shard1", "2@shard1", "3@shard2", "4@shard2"); reconciler.apply("1@shard1", data -> Mono.just("1")).block(); expectEvent(eventIt, SimpleReconcilerEvent.Kind.Updated, "1@shard1", "1"); assertThat(reconciler.getAll()).containsEntry("1@shard1", "1"); reconciler.apply("4@shard2", data -> Mono.just("2")).block(); expectEvent(eventIt, SimpleReconcilerEvent.Kind.Updated, "4@shard2", "2"); } @Test(timeout = 30_000) public void testRemove() { Iterator<List<SimpleReconcilerEvent<String>>> eventId = addData("1@shard1", "2@shard1", "3@shard2", "4@shard2"); reconciler.remove("1@shard1").block(); expectEvent(eventId, SimpleReconcilerEvent.Kind.Removed, "1@shard1", ""); reconciler.remove("3@shard2").block(); expectEvent(eventId, SimpleReconcilerEvent.Kind.Removed, "3@shard2", ""); assertThat(shard1.getAll()).hasSize(1).containsKey("2@shard1"); assertThat(shard2.getAll()).hasSize(1).containsKey("4@shard2"); } @Test(timeout = 30_000) public void testGetAllAndSize() { addData("1@shard1", "2@shard1", "3@shard2", "4@shard2"); assertThat(reconciler.getAll()).containsKeys("1@shard1", "2@shard1", "3@shard2", "4@shard2"); assertThat(reconciler.size()).isEqualTo(4); } @Test(timeout = 30_000) public void testFindById() { addData("1@shard1", "2@shard1", "3@shard2", "4@shard2"); assertThat(reconciler.findById("1@shard1")).isNotEmpty(); assertThat(reconciler.findById("4@shard2")).isNotEmpty(); assertThat(reconciler.findById("wrongId")).isEmpty(); } @Test public void testClose() { reconciler.close().block(); try { reconciler.add("abc", "v").block(); fail("Expected add failure"); } catch (Exception e) { assertThat(e).isInstanceOf(IllegalStateException.class); assertThat(e.getMessage()).contains("Sharded reconciler closed"); } } private Iterator<List<SimpleReconcilerEvent<String>>> addData(String... ids) { for (String id : ids) { reconciler.add(id, "").block(); } Iterator<List<SimpleReconcilerEvent<String>>> eventsIt = reconciler.changes("junit").toIterable().iterator(); assertThat(eventsIt.hasNext()).isTrue(); List<SimpleReconcilerEvent<String>> next = eventsIt.next(); assertThat(next).hasSize(ids.length); return eventsIt; } private void expectEvent(Iterator<List<SimpleReconcilerEvent<String>>> eventsIt, SimpleReconcilerEvent.Kind kind, String id, String value) { assertThat(eventsIt.hasNext()).isTrue(); List<SimpleReconcilerEvent<String>> next = eventsIt.next(); assertThat(next).hasSize(1); assertThat(next.get(0).getKind()).isEqualTo(kind); assertThat(next.get(0).getId()).isEqualTo(id); assertThat(next.get(0).getData()).isEqualTo(value); } }
585
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/framework/simplereconciler
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/framework/simplereconciler/internal/SnapshotMergerTest.java
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.simplereconciler.internal; import java.util.Arrays; import java.util.Iterator; import java.util.List; import com.netflix.titus.common.util.tuple.Pair; import org.junit.Test; import reactor.core.publisher.Flux; import static org.assertj.core.api.Assertions.assertThat; public class SnapshotMergerTest { @Test public void testMergeSnapshots() { List<List<String>> stream1 = Arrays.asList( Arrays.asList("stream1_snapshot_value1", "stream1_snapshot_value2"), Arrays.asList("stream1_update_value1", "stream1_update_value2") ); List<List<String>> stream2 = Arrays.asList( Arrays.asList("stream2_snapshot_value1", "stream2_snapshot_value2"), Arrays.asList("stream2_update_value1", "stream2_update_value2") ); Flux<List<String>> events = SnapshotMerger.mergeWithSingleSnapshot(Arrays.asList( Flux.fromIterable(stream1), Flux.fromIterable(stream2) )); Iterator<List<String>> eventIt = events.toIterable().iterator(); assertThat(eventIt.hasNext()).isTrue(); List<String> snapshot = eventIt.next(); assertThat(snapshot).containsExactly( "stream1_snapshot_value1", "stream1_snapshot_value2", "stream2_snapshot_value1", "stream2_snapshot_value2"); assertThat(eventIt.hasNext()).isTrue(); List<String> updates1 = eventIt.next(); assertThat(updates1).containsExactly("stream1_update_value1", "stream1_update_value2"); assertThat(eventIt.hasNext()).isTrue(); List<String> updates2 = eventIt.next(); assertThat(updates2).containsExactly("stream2_update_value1", "stream2_update_value2"); } @Test public void testIndexedMergeSnapshots() { Flux<Pair<String, List<String>>> stream1 = Flux.fromIterable(Arrays.asList( Arrays.asList("stream1_snapshot_value1", "stream1_snapshot_value2"), Arrays.asList("stream1_update_value1", "stream1_update_value2") )) .map(list -> Pair.of("stream1", list)); Flux<Pair<String, List<String>>> stream2 = Flux.fromIterable(Arrays.asList( Arrays.asList("stream2_snapshot_value1", "stream2_snapshot_value2"), Arrays.asList("stream2_update_value1", "stream2_update_value2") )) .map(list -> Pair.of("stream2", list)); Flux<List<String>> events = SnapshotMerger.mergeIndexedStreamWithSingleSnapshot(Arrays.asList(stream1, stream2)); Iterator<List<String>> eventIt = events.toIterable().iterator(); assertThat(eventIt.hasNext()).isTrue(); List<String> snapshot = eventIt.next(); assertThat(snapshot).containsExactly( "stream1_snapshot_value1", "stream1_snapshot_value2", "stream2_snapshot_value1", "stream2_snapshot_value2"); assertThat(eventIt.hasNext()).isTrue(); List<String> updates1 = eventIt.next(); assertThat(updates1).containsExactly("stream1_update_value1", "stream1_update_value2"); assertThat(eventIt.hasNext()).isTrue(); List<String> updates2 = eventIt.next(); assertThat(updates2).containsExactly("stream2_update_value1", "stream2_update_value2"); } }
586
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/framework/simplereconciler
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/framework/simplereconciler/internal/StubManyReconciler.java
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.simplereconciler.internal; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Function; import com.google.common.base.Preconditions; import com.netflix.titus.common.framework.simplereconciler.ManyReconciler; import com.netflix.titus.common.framework.simplereconciler.SimpleReconcilerEvent; import com.netflix.titus.common.util.collections.index.IndexSet; import com.netflix.titus.common.util.collections.index.Indexes; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.core.publisher.Sinks; class StubManyReconciler<DATA> implements ManyReconciler<DATA> { private final ConcurrentMap<String, DATA> state = new ConcurrentHashMap<>(); private final AtomicLong transactionIds = new AtomicLong(); private final Sinks.Many<List<SimpleReconcilerEvent<DATA>>> eventSink = Sinks.many().multicast().directAllOrNothing(); private final List<List<SimpleReconcilerEvent<DATA>>> eventsCollector = new CopyOnWriteArrayList<>(); @Override public Mono<Void> add(String id, DATA initial) { return Mono.fromRunnable(() -> { Preconditions.checkState(!state.containsKey(id)); state.put(id, initial); emitEvent(SimpleReconcilerEvent.Kind.Added, id, initial); }); } @Override public Mono<Void> remove(String id) { return Mono.fromRunnable(() -> { Preconditions.checkState(state.containsKey(id)); DATA value = state.remove(id); emitEvent(SimpleReconcilerEvent.Kind.Removed, id, value); }); } @Override public Mono<Void> close() { return Mono.empty(); } @Override public Map<String, DATA> getAll() { return new HashMap<>(state); } @Override public IndexSet<String, DATA> getIndexSet() { return Indexes.empty(); } @Override public Optional<DATA> findById(String id) { return Optional.ofNullable(state.get(id)); } @Override public int size() { return state.size(); } @Override public Mono<DATA> apply(String id, Function<DATA, Mono<DATA>> action) { return Mono.defer(() -> { Preconditions.checkState(state.containsKey(id)); return action.apply(state.get(id)).doOnNext(newValue -> { state.put(id, newValue); emitEvent(SimpleReconcilerEvent.Kind.Updated, id, newValue); }); }); } @Override public Flux<List<SimpleReconcilerEvent<DATA>>> changes(String clientId) { List<SimpleReconcilerEvent<DATA>> snapshot = new ArrayList<>(); state.forEach((id, value) -> snapshot.add(new SimpleReconcilerEvent<>(SimpleReconcilerEvent.Kind.Added, id, value, transactionIds.getAndIncrement()))); return Flux.just(snapshot).concatWith(eventSink.asFlux()); } private void emitEvent(SimpleReconcilerEvent.Kind kind, String id, DATA value) { List<SimpleReconcilerEvent<DATA>> events = Collections.singletonList( new SimpleReconcilerEvent<>(kind, id, value, transactionIds.getAndIncrement()) ); eventsCollector.add(events); eventSink.emitNext(events, Sinks.EmitFailureHandler.FAIL_FAST); } }
587
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/framework/simplereconciler
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/framework/simplereconciler/internal/DefaultManyReconcilerTest.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.simplereconciler.internal; import java.time.Duration; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; import com.google.common.base.Preconditions; import com.netflix.titus.common.framework.simplereconciler.ReconcilerActionProvider; import com.netflix.titus.common.framework.simplereconciler.ReconcilerActionProviderPolicy; import com.netflix.titus.common.framework.simplereconciler.SimpleReconcilerEvent; import com.netflix.titus.common.framework.simplereconciler.internal.provider.ActionProviderSelectorFactory; import com.netflix.titus.common.framework.simplereconciler.internal.provider.SampleActionProviderCatalog; import com.netflix.titus.common.framework.simplereconciler.internal.provider.SampleActionProviderCatalog.SampleProviderActionFunction; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.runtime.TitusRuntimes; import com.netflix.titus.common.util.Evaluators; import com.netflix.titus.common.util.closeable.CloseableReference; import com.netflix.titus.common.util.collections.index.IndexSetHolderBasic; import com.netflix.titus.common.util.collections.index.IndexSpec; import com.netflix.titus.common.util.collections.index.Indexes; import com.netflix.titus.common.util.rx.ReactorExt; import com.netflix.titus.testkit.rx.TitusRxSubscriber; import org.junit.After; import org.junit.Test; import reactor.core.Disposable; import reactor.core.publisher.Mono; import reactor.core.scheduler.Scheduler; import reactor.core.scheduler.Schedulers; import static com.jayway.awaitility.Awaitility.await; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; public class DefaultManyReconcilerTest { private static final Duration TIMEOUT = Duration.ofSeconds(5); private static final String INDEX_ID = "reversed"; private final TitusRuntime titusRuntime = TitusRuntimes.internal(); private DefaultManyReconciler<String> reconciler; private TitusRxSubscriber<List<SimpleReconcilerEvent<String>>> changesSubscriber; @After public void tearDown() { ReactorExt.safeDispose(changesSubscriber); Evaluators.acceptNotNull(reconciler, r -> r.close().block(TIMEOUT)); } @Test public void testExternalAction() throws InterruptedException { newReconcilerWithRegistrations(data -> Collections.emptyList()); // Register reconciler.add("r1", "a").block(); assertThat(reconciler.findById("r1")).contains("a"); expectAddEvent("r1", "a"); // Make changes assertThat(reconciler.apply("r1", current -> Mono.just(current.toUpperCase())).block()).isEqualTo("A"); expectUpdateEvent("r1", "A"); // Close reconciler.remove("r1").block(); assertThat(reconciler.findById("r1")).isEmpty(); expectRemovedEvent("r1", "A"); } @Test public void testExternalActionCancel() throws InterruptedException { newReconcilerWithRegistrations(data -> Collections.emptyList(), "r1", "a"); CountDownLatch subscribeLatch = new CountDownLatch(1); AtomicBoolean canceled = new AtomicBoolean(); Mono<String> action = Mono.<String>never() .doOnSubscribe(s -> subscribeLatch.countDown()) .doOnCancel(() -> canceled.set(true)); Disposable disposable = reconciler.apply("r1", data -> action).subscribe(); subscribeLatch.await(); assertThat(disposable.isDisposed()).isFalse(); assertThat(canceled.get()).isFalse(); disposable.dispose(); await().until(canceled::get); assertThat(changesSubscriber.takeNext()).isNull(); // Now run regular action assertThat(reconciler.apply("r1", anything -> Mono.just("Regular")).block(TIMEOUT)).isEqualTo("Regular"); } @Test public void testExternalActionMonoError() throws InterruptedException { newReconcilerWithRegistrations(current -> Collections.emptyList(), "r1", "a"); try { reconciler.apply("r1", anything -> Mono.error(new RuntimeException("simulated error"))).block(); fail("Expected error"); } catch (Exception e) { assertThat(e).isInstanceOf(RuntimeException.class); assertThat(e.getMessage()).isEqualTo("simulated error"); } assertThat(changesSubscriber.takeNext()).isNull(); } @Test public void testExternalActionFunctionError() throws InterruptedException { newReconcilerWithRegistrations(current -> Collections.emptyList(), "r1", "a"); try { reconciler.apply("r1", c -> { throw new RuntimeException("simulated error"); }).block(); fail("Expected error"); } catch (Exception e) { assertThat(e).isInstanceOf(RuntimeException.class); assertThat(e.getMessage()).isEqualTo("simulated error"); } assertThat(changesSubscriber.takeNext()).isNull(); } @Test public void testReconcilerAction() throws InterruptedException { newReconcilerWithRegistrations( dataBefore -> dataBefore.equals("a") ? Collections.singletonList(Mono.just(dataAfter -> "b")) : Collections.emptyList(), "r1", "a" ); await().until(() -> reconciler.findById("r1").orElse("").equals("b")); } /** * Internal reconciler runs periodically and emits events constantly. The event dispatcher does not do any * deduplication, so if run without any control, the subscriber would be getting different number of items * on each emit. To avoid that we instruct the reconciler here when to emit the items we want. */ @Test public void testReconcilerActionMonoError() throws InterruptedException { AtomicInteger roundRef = new AtomicInteger(-1); newReconcilerWithRegistrations( dataBefore -> { if (roundRef.get() == -1) { return Collections.emptyList(); } if (roundRef.getAndIncrement() == 0) { return Collections.singletonList(Mono.error(new RuntimeException("simulated error"))); } roundRef.set(-1); return Collections.singletonList(Mono.just(v -> "A")); }, "r1", "a" ); roundRef.set(0); expectUpdateEvent("r1", "A"); } /** * Check {@link #testReconcilerActionMonoError()} to understand the logic of this test. */ @Test public void testReconcilerActionFunctionError() throws InterruptedException { AtomicInteger roundRef = new AtomicInteger(-1); newReconcilerWithRegistrations( dataBefore -> { if (roundRef.get() == -1) { return Collections.emptyList(); } return Collections.singletonList(Mono.just(dataAfter -> { if (roundRef.getAndIncrement() == 0) { throw new RuntimeException("simulated error"); } roundRef.set(-1); return "A"; })); }, "r1", "a" ); roundRef.set(0); expectUpdateEvent("r1", "A"); } @Test public void testReconcilerCloseWithRunningExternalAction() throws InterruptedException { newReconcilerWithRegistrations( current -> Collections.emptyList(), "r1", "a", "r2", "b" ); TitusRxSubscriber<String> subscriber1 = new TitusRxSubscriber<>(); TitusRxSubscriber<String> subscriber2 = new TitusRxSubscriber<>(); reconciler.apply("r1", c -> Mono.never()).subscribe(subscriber1); reconciler.apply("r2", c -> Mono.never()).subscribe(subscriber2); assertThat(subscriber1.isOpen()).isTrue(); assertThat(subscriber2.isOpen()).isTrue(); reconciler.close().subscribe(); await().until(() -> !subscriber1.isOpen()); await().until(() -> !subscriber2.isOpen()); assertThat(subscriber1.getError().getMessage()).isEqualTo("cancelled"); assertThat(subscriber2.getError().getMessage()).isEqualTo("cancelled"); await().until(() -> !changesSubscriber.isOpen()); } @Test public void testReconcilerCloseWithRunningReconciliationAction() throws InterruptedException { // Start reconciliation action first CountDownLatch ready = new CountDownLatch(1); AtomicBoolean cancelled = new AtomicBoolean(); Mono<Function<String, String>> action = Mono.<Function<String, String>>never() .doOnSubscribe(s -> ready.countDown()) .doOnCancel(() -> cancelled.set(true)); newReconcilerWithRegistrations(current -> Collections.singletonList(action), "r1", "a"); ready.await(); TitusRxSubscriber<String> subscriber = new TitusRxSubscriber<>(); reconciler.apply("r1", c -> Mono.never()).subscribe(subscriber); assertThat(subscriber.isOpen()).isTrue(); reconciler.close().subscribe(); await().until(() -> cancelled.get() && !subscriber.isOpen()); assertThat(subscriber.getError().getMessage()).isEqualTo("cancelled"); await().until(() -> !changesSubscriber.isOpen()); } @Test public void testActionProviderPriorities() throws InterruptedException { ReconcilerActionProvider<String> provider1 = SampleActionProviderCatalog.newInternalProvider("i1", 20); ReconcilerActionProvider<String> provider2 = SampleActionProviderCatalog.newInternalProvider("i2", 1_000, Duration.ZERO, Duration.ofMillis(10)); ((SampleProviderActionFunction) provider1.getActionProvider()).enableEmit(true); ((SampleProviderActionFunction) provider2.getActionProvider()).enableEmit(true); ActionProviderSelectorFactory<String> selectorFactory = new ActionProviderSelectorFactory<>("test", Arrays.asList( new ReconcilerActionProvider<>(ReconcilerActionProviderPolicy.getDefaultExternalPolicy(), true, data -> Collections.emptyList()), provider1, provider2 ), titusRuntime); newReconcilerWithRegistrations(selectorFactory, "a", ""); await().timeout(com.jayway.awaitility.Duration.FOREVER).until(() -> reconciler.getAll().get("a").contains("i2")); } @Test public void testIndex() throws InterruptedException { newReconcilerWithRegistrations(data -> Collections.emptyList(), "i1", "i1_v1", "i2", "i2_v2"); assertThat(reconciler.getIndexSet().getOrder(INDEX_ID).orderedList()).hasSize(2).containsSequence("i1_v1", "i2_v2"); // Register reconciler.add("i3", "i3_v3").block(); assertThat(reconciler.getIndexSet().getOrder(INDEX_ID).orderedList()).hasSize(3).containsSequence("i1_v1", "i2_v2", "i3_v3"); // Make changes reconciler.apply("i3", current -> Mono.just("i3_v3a")).block(); assertThat(reconciler.getIndexSet().getOrder(INDEX_ID).orderedList()).hasSize(3).containsSequence("i1_v1", "i2_v2", "i3_v3a"); // Close reconciler.remove("i3").block(); assertThat(reconciler.getIndexSet().getOrder(INDEX_ID).orderedList()).hasSize(2).containsSequence("i1_v1", "i2_v2"); } private void newReconcilerWithRegistrations(Function<String, List<Mono<Function<String, String>>>> reconcilerActionsProvider, String... idAndInitialValuePairs) throws InterruptedException { ActionProviderSelectorFactory<String> selectorFactory = new ActionProviderSelectorFactory<>("test", Arrays.asList( new ReconcilerActionProvider<>(ReconcilerActionProviderPolicy.getDefaultExternalPolicy(), true, data -> Collections.emptyList()), new ReconcilerActionProvider<>(ReconcilerActionProviderPolicy.getDefaultInternalPolicy(), false, reconcilerActionsProvider) ), titusRuntime); newReconcilerWithRegistrations(selectorFactory, idAndInitialValuePairs); } private void newReconcilerWithRegistrations(ActionProviderSelectorFactory<String> selectorFactory, String... idAndInitialValuePairs) throws InterruptedException { Preconditions.checkArgument((idAndInitialValuePairs.length % 2) == 0, "Expected pairs of id/value"); CloseableReference<Scheduler> reconcilerSchedulerRef = CloseableReference.referenceOf(Schedulers.newSingle("reconciler"), Scheduler::dispose); CloseableReference<Scheduler> notificationSchedulerRef = CloseableReference.referenceOf(Schedulers.newSingle("notification"), Scheduler::dispose); Function<String, String> keyExtractor = s -> s.substring(0, Math.min(s.length(), 2)); IndexSetHolderBasic<String, String> indexSetHolder = new IndexSetHolderBasic<>(Indexes.<String, String>newBuilder() .withOrder(INDEX_ID, IndexSpec.<String, String, String, String>newBuilder() .withPrimaryKeyComparator(String::compareTo) .withIndexKeyComparator(String::compareTo) .withPrimaryKeyExtractor(keyExtractor) .withIndexKeyExtractor(keyExtractor) .build() ) .build() ); reconciler = new DefaultManyReconciler<>( "junit", Duration.ofMillis(1), Duration.ofMillis(2), selectorFactory, reconcilerSchedulerRef, notificationSchedulerRef, indexSetHolder, Indexes.monitor( titusRuntime.getRegistry().createId(ReconcilerExecutorMetrics.ROOT_NAME + "indexes"), indexSetHolder, titusRuntime.getRegistry() ), titusRuntime ); for (int i = 0; i < idAndInitialValuePairs.length; i += 2) { reconciler.add(idAndInitialValuePairs[i], idAndInitialValuePairs[i + 1]).block(TIMEOUT); } reconciler.changes().subscribe(changesSubscriber = new TitusRxSubscriber<>()); List<SimpleReconcilerEvent<String>> snapshot = changesSubscriber.takeNext(TIMEOUT); assertThat(snapshot).hasSize(idAndInitialValuePairs.length / 2); } private void expectAddEvent(String id, String data) throws InterruptedException { expectEvent(id, data, SimpleReconcilerEvent.Kind.Added); } private void expectUpdateEvent(String id, String data) throws InterruptedException { expectEvent(id, data, SimpleReconcilerEvent.Kind.Updated); } private void expectRemovedEvent(String id, String data) throws InterruptedException { expectEvent(id, data, SimpleReconcilerEvent.Kind.Removed); } private void expectEvent(String id, String data, SimpleReconcilerEvent.Kind kind) throws InterruptedException { List<SimpleReconcilerEvent<String>> addEvent = changesSubscriber.takeNext(TIMEOUT); assertThat(addEvent).hasSize(1); assertThat(addEvent.get(0).getKind()).isEqualTo(kind); assertThat(addEvent.get(0).getId()).isEqualTo(id); assertThat(addEvent.get(0).getData()).isEqualTo(data); } }
588
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/framework/simplereconciler/internal
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/framework/simplereconciler/internal/provider/ActionProviderSelectorTest.java
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.simplereconciler.internal.provider; import java.time.Duration; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import com.netflix.titus.common.framework.simplereconciler.ReconcilerActionProvider; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.runtime.TitusRuntimes; import com.netflix.titus.common.util.time.Clocks; import com.netflix.titus.common.util.time.TestClock; import org.junit.Before; import org.junit.Test; import static com.netflix.titus.common.framework.simplereconciler.internal.provider.SampleActionProviderCatalog.newExternalProvider; import static com.netflix.titus.common.framework.simplereconciler.internal.provider.SampleActionProviderCatalog.newInternalProvider; import static org.assertj.core.api.Assertions.assertThat; public class ActionProviderSelectorTest { private final TestClock testClock = Clocks.test(); private final TitusRuntime titusRuntime = TitusRuntimes.test(testClock); @Before public void setUp() throws Exception { testClock.advanceTime(Duration.ofMillis(1_000)); } @Test public void testSingleProvider() { ActionProviderSelector<String> selector = new ActionProviderSelector<>("test", Collections.singletonList(newExternalProvider("a")), titusRuntime); Iterator<ReconcilerActionProvider<String>> it = selector.next(testClock.wallTime()); expectExternal(it, "a"); assertThat(it.hasNext()).isFalse(); } @Test public void testTwoProvider() { ActionProviderSelector<String> selector = new ActionProviderSelector<>("test", Arrays.asList( newExternalProvider("a"), newInternalProvider("b", 1_000) ), titusRuntime); Iterator<ReconcilerActionProvider<String>> it = selector.next(testClock.wallTime()); expectExternal(it, "a"); expectInternal(it, "b"); assertThat(it.hasNext()).isFalse(); } @Test public void testManyProvider() { ActionProviderSelector<String> selector = new ActionProviderSelector<>("test", Arrays.asList( newExternalProvider("a"), newInternalProvider("b", 2_000), newInternalProvider("c", 1_000) ), titusRuntime); Iterator<ReconcilerActionProvider<String>> it = selector.next(testClock.wallTime()); expectExternal(it, "a"); expectInternal(it, "c"); expectInternal(it, "b"); assertThat(it.hasNext()).isFalse(); } @Test public void testProviderWithExecutionInterval() { ActionProviderSelector<String> selector = new ActionProviderSelector<>("test", Arrays.asList( newExternalProvider("a"), newInternalProvider("b", 1, Duration.ofMillis(1_000), Duration.ZERO) ), titusRuntime); testClock.advanceTime(Duration.ofMillis(10_000)); Iterator<ReconcilerActionProvider<String>> it = selector.next(testClock.wallTime()); expectInternal(it, "b"); expectExternal(it, "a"); assertThat(it.hasNext()).isFalse(); selector.updateEvaluationTime("b", testClock.wallTime()); it = selector.next(testClock.wallTime()); expectExternal(it, "a"); assertThat(it.hasNext()).isFalse(); testClock.advanceTime(Duration.ofMillis(1_000)); } @Test public void testProviderWithMinExecutionInterval() { ActionProviderSelector<String> selector = new ActionProviderSelector<>("test", Arrays.asList( newExternalProvider("a"), newInternalProvider("b", 1_000, Duration.ZERO, Duration.ofMillis(10_000)) ), titusRuntime); Iterator<ReconcilerActionProvider<String>> it = selector.next(testClock.wallTime()); expectExternal(it, "a"); expectInternal(it, "b"); assertThat(it.hasNext()).isFalse(); testClock.advanceTime(Duration.ofMillis(10_000)); it = selector.next(testClock.wallTime()); expectInternal(it, "b"); expectExternal(it, "a"); assertThat(it.hasNext()).isFalse(); selector.updateEvaluationTime("b", 10_000); it = selector.next(testClock.wallTime()); expectExternal(it, "a"); expectInternal(it, "b"); assertThat(it.hasNext()).isFalse(); } @Test public void testTwoProvidersWithSamePriority() { ActionProviderSelector<String> selector = new ActionProviderSelector<>("test", Arrays.asList( newInternalProvider("a", 1_000, Duration.ZERO, Duration.ZERO), newInternalProvider("b", 1_000, Duration.ZERO, Duration.ZERO) ), titusRuntime); Iterator<ReconcilerActionProvider<String>> it = selector.next(testClock.wallTime()); ReconcilerActionProvider<String> next = it.next(); if (next.getPolicy().getName().equals("a")) { expectInternal(it, "b"); selector.updateEvaluationTime("a", testClock.wallTime()); it = selector.next(testClock.wallTime()); expectInternal(it, "b"); expectInternal(it, "a"); } else { expectInternal(it, "a"); selector.updateEvaluationTime("b", testClock.wallTime()); it = selector.next(testClock.wallTime()); expectInternal(it, "a"); expectInternal(it, "b"); } } private void expect(Iterator<ReconcilerActionProvider<String>> it, String name, boolean external) { assertThat(it.hasNext()).isTrue(); ReconcilerActionProvider<String> next = it.next(); assertThat(next.getPolicy().getName()).isEqualTo(name); assertThat(next.isExternal()).isEqualTo(external); } private void expectExternal(Iterator<ReconcilerActionProvider<String>> it, String name) { expect(it, name, true); } private void expectInternal(Iterator<ReconcilerActionProvider<String>> it, String name) { expect(it, name, false); } }
589
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/framework/simplereconciler/internal
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/framework/simplereconciler/internal/provider/SampleActionProviderCatalog.java
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.simplereconciler.internal.provider; import java.time.Duration; import java.util.Collections; import java.util.List; import java.util.function.Function; import com.netflix.titus.common.framework.simplereconciler.ReconcilerActionProvider; import com.netflix.titus.common.framework.simplereconciler.ReconcilerActionProviderPolicy; import reactor.core.publisher.Mono; public class SampleActionProviderCatalog { private static final Function<String, List<Mono<Function<String, String>>>> NO_OP = d -> Collections.emptyList(); public static ReconcilerActionProvider<String> newExternalProvider(String name) { return new ReconcilerActionProvider<>( ReconcilerActionProviderPolicy.getDefaultExternalPolicy().toBuilder().withName(name).build(), true, NO_OP ); } public static ReconcilerActionProvider<String> newInternalProvider(String name, int priority, Duration executionInterval, Duration minExecutionInterval) { return new ReconcilerActionProvider<>( ReconcilerActionProviderPolicy.getDefaultInternalPolicy().toBuilder() .withName(name) .withPriority(priority) .withExecutionInterval(executionInterval) .withMinimumExecutionInterval(minExecutionInterval) .build(), false, new SampleProviderActionFunction("#" + name) ); } public static ReconcilerActionProvider<String> newInternalProvider(String name, int priority) { return newInternalProvider(name, priority, Duration.ZERO, Duration.ZERO); } public static class SampleProviderActionFunction implements Function<String, List<Mono<Function<String, String>>>> { private final String suffixToAdd; private boolean emitEnabled; public SampleProviderActionFunction(String suffixToAdd) { this.suffixToAdd = suffixToAdd; } public void enableEmit(boolean emitEnabled) { this.emitEnabled = emitEnabled; } @Override public List<Mono<Function<String, String>>> apply(String data) { if (emitEnabled) { return Collections.singletonList(Mono.just(d -> d + suffixToAdd)); } return Collections.emptyList(); } } }
590
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/framework
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/framework/reconciler/EntityHolderTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.reconciler; import java.util.Optional; import com.netflix.titus.common.util.tuple.Pair; import org.junit.Test; import static com.netflix.titus.common.framework.reconciler.EntityHolder.newRoot; import static com.netflix.titus.common.util.CollectionsExt.first; import static org.assertj.core.api.Assertions.assertThat; public class EntityHolderTest { @Test public void testParentChildRelationShip() throws Exception { EntityHolder child = newRoot("myChild", "a1"); EntityHolder root = newRoot("myRoot", "as").addChild(child); // Check root assertThat(root.getId()).isEqualTo("myRoot"); assertThat((String) root.getEntity()).isEqualTo("as"); assertThat(root.getChildren()).hasSize(1); assertThat(first(root.getChildren()) == child).isTrue(); // Check child assertThat(child.getId()).isEqualTo("myChild"); assertThat((String) child.getEntity()).isEqualTo("a1"); } @Test public void testExistingChildGetsUpdated() throws Exception { EntityHolder rootV1 = newRoot("myRoot", "as").addChild(newRoot("myChild", "a1")); EntityHolder rootV2 = rootV1.addChild(newRoot("myChild", "a1_v2")); assertThat((String) first(rootV2.getChildren()).getEntity()).isEqualTo("a1_v2"); } @Test public void testRemoveFromParent() throws Exception { EntityHolder rootV1 = newRoot("myRoot", "as") .addChild(newRoot("myChild1", "a1")) .addChild(newRoot("myChild2", "a2")); Pair<EntityHolder, Optional<EntityHolder>> rootChildPair = rootV1.removeChild("myChild1"); EntityHolder rootV2 = rootChildPair.getLeft(); EntityHolder child1 = rootChildPair.getRight().get(); assertThat(rootV2.getChildren()).hasSize(1); assertThat(first(rootV2.getChildren()).getId()).isEqualTo("myChild2"); assertThat(child1.getId()).isEqualTo("myChild1"); } }
591
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/framework/reconciler
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/framework/reconciler/internal/SimpleReconcilerEventFactory.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.reconciler.internal; import java.util.Optional; import com.netflix.titus.common.framework.reconciler.ChangeAction; import com.netflix.titus.common.framework.reconciler.EntityHolder; import com.netflix.titus.common.framework.reconciler.ModelActionHolder; import com.netflix.titus.common.framework.reconciler.ReconcileEventFactory; import com.netflix.titus.common.framework.reconciler.ReconciliationEngine; /** * */ public class SimpleReconcilerEventFactory implements ReconcileEventFactory<SimpleReconcilerEvent> { @Override public SimpleReconcilerEvent newCheckpointEvent(long timestamp) { return new SimpleReconcilerEvent(SimpleReconcilerEvent.EventType.Checkpoint, "checkpoint: " + timestamp, Optional.empty()); } @Override public SimpleReconcilerEvent newBeforeChangeEvent(ReconciliationEngine engine, ChangeAction changeAction, String transactionId) { return new SimpleReconcilerEvent(SimpleReconcilerEvent.EventType.ChangeRequest, changeAction.toString(), Optional.empty()); } @Override public SimpleReconcilerEvent newAfterChangeEvent(ReconciliationEngine engine, ChangeAction changeAction, long waitTimeMs, long executionTimeMs, String transactionId) { return new SimpleReconcilerEvent(SimpleReconcilerEvent.EventType.Changed, changeAction.toString(), Optional.empty()); } @Override public SimpleReconcilerEvent newChangeErrorEvent(ReconciliationEngine engine, ChangeAction changeAction, Throwable error, long waitTimeMs, long executionTimeMs, String transactionId) { return new SimpleReconcilerEvent(SimpleReconcilerEvent.EventType.ChangeError, changeAction.toString(), Optional.of(error)); } @Override public SimpleReconcilerEvent newModelEvent(ReconciliationEngine engine, EntityHolder newRoot) { return new SimpleReconcilerEvent(SimpleReconcilerEvent.EventType.ModelInitial, "init", Optional.empty()); } @Override public SimpleReconcilerEvent newModelUpdateEvent(ReconciliationEngine engine, ChangeAction changeAction, ModelActionHolder modelActionHolder, EntityHolder changedEntityHolder, Optional previousEntityHolder, String transactionId) { return new SimpleReconcilerEvent(SimpleReconcilerEvent.EventType.ModelUpdated, changedEntityHolder.getEntity(), Optional.empty()); } @Override public SimpleReconcilerEvent newModelUpdateErrorEvent(ReconciliationEngine engine, ChangeAction changeAction, ModelActionHolder modelActionHolder, EntityHolder previousEntityHolder, Throwable error, String transactionId) { return new SimpleReconcilerEvent(SimpleReconcilerEvent.EventType.ModelUpdateError, previousEntityHolder.getEntity(), Optional.of(error)); } }
592
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/framework/reconciler
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/framework/reconciler/internal/EngineStub.java
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.reconciler.internal; import java.util.List; import com.netflix.titus.common.framework.reconciler.ChangeAction; import com.netflix.titus.common.framework.reconciler.EntityHolder; import com.netflix.titus.common.framework.reconciler.ReconciliationEngine; import rx.Observable; import rx.subjects.PublishSubject; class EngineStub implements ReconciliationEngine<SimpleReconcilerEvent> { private final String id; private final EntityHolder referenceView; private final PublishSubject<SimpleReconcilerEvent> eventSubject = PublishSubject.create(); EngineStub(String id) { this.id = id; this.referenceView = EntityHolder.newRoot(id, "initial"); } @Override public Observable<Void> changeReferenceModel(ChangeAction changeAction) { throw new IllegalStateException("not implemented yet"); } @Override public Observable<Void> changeReferenceModel(ChangeAction changeAction, String entityHolderId) { throw new IllegalStateException("not implemented yet"); } @Override public EntityHolder getReferenceView() { return referenceView; } @Override public EntityHolder getRunningView() { throw new IllegalStateException("not implemented yet"); } @Override public EntityHolder getStoreView() { throw new IllegalStateException("not implemented yet"); } @Override public <ORDER_BY> List<EntityHolder> orderedView(ORDER_BY orderingCriteria) { throw new IllegalStateException("not implemented yet"); } @Override public Observable<SimpleReconcilerEvent> events() { return eventSubject; } public void emitChange(String... changes) { for(String change: changes) { eventSubject.onNext(SimpleReconcilerEvent.newChange(change)); } } }
593
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/framework/reconciler
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/framework/reconciler/internal/EventDistributorTest.java
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.reconciler.internal; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.runtime.TitusRuntimes; import org.junit.Test; import rx.Emitter; import rx.Observable; import rx.Subscription; import static org.assertj.core.api.Assertions.assertThat; public class EventDistributorTest { private static final TitusRuntime titusRuntime = TitusRuntimes.internal(); private static final long CHECKPOINT_INTERVAL_MS = 10; private final EventDistributor<SimpleReconcilerEvent> eventDistributor = new EventDistributor<>( new SimpleReconcilerEventFactory(), CHECKPOINT_INTERVAL_MS, titusRuntime.getRegistry() ); @Test public void testBootstrap() throws Exception { EngineStub engine1 = new EngineStub("engine1"); EngineStub engine2 = new EngineStub("engine2"); eventDistributor.connectReconciliationEngine(engine1); eventDistributor.connectReconciliationEngine(engine2); eventDistributor.start(); MyClient client = new MyClient(); eventDistributor.connectEmitter(client.getEmitter()); engine1.emitChange("engine1/change1"); engine2.emitChange("engine2/change1", "engine2/change2"); engine1.emitChange("engine1/change2"); client.expectChanges("engine1/change1", "engine2/change1", "engine2/change2", "engine1/change2"); } @Test public void testEngineAddRemove() throws Exception { eventDistributor.start(); EngineStub engine1 = new EngineStub("engine1"); EngineStub engine2 = new EngineStub("engine2"); eventDistributor.connectReconciliationEngine(engine1); eventDistributor.connectReconciliationEngine(engine2); MyClient client = new MyClient(); eventDistributor.connectEmitter(client.getEmitter()); engine1.emitChange("engine1/change1"); engine2.emitChange("engine2/change1"); client.expectChanges("engine1/change1", "engine2/change1"); eventDistributor.removeReconciliationEngine(engine1); engine1.emitChange("engine1/change2"); engine2.emitChange("engine2/change2"); client.expectChanges("engine2/change2"); } @Test public void testClientAddUnsubscribe() throws Exception { eventDistributor.start(); EngineStub engine1 = new EngineStub("engine1"); eventDistributor.connectReconciliationEngine(engine1); MyClient client1 = new MyClient(); eventDistributor.connectEmitter(client1.getEmitter()); MyClient client2 = new MyClient(); eventDistributor.connectEmitter(client2.getEmitter()); engine1.emitChange("engine1/change1"); client1.expectChanges("engine1/change1"); client2.expectChanges("engine1/change1"); client1.unsubscribe(); client1.drainCheckpoints(); engine1.emitChange("engine1/change2"); client2.expectChanges("engine1/change2"); client1.expectNoEvents(); } @Test public void testShutdown() throws Exception { eventDistributor.start(); EngineStub engine1 = new EngineStub("engine1"); eventDistributor.connectReconciliationEngine(engine1); MyClient client1 = new MyClient(); eventDistributor.connectEmitter(client1.getEmitter()); engine1.emitChange("engine1/change1"); client1.expectChanges("engine1/change1"); eventDistributor.stop(30_000); client1.expectStopped(); } static class MyClient { private Emitter<SimpleReconcilerEvent> emitter; private final LinkedBlockingQueue<SimpleReconcilerEvent> receivedEvents = new LinkedBlockingQueue<>(); private final Subscription subscription; private volatile Throwable error; private volatile boolean completed; MyClient() { Observable<SimpleReconcilerEvent> observable = Observable.create(emitter -> { MyClient.this.emitter = emitter; }, Emitter.BackpressureMode.ERROR); this.subscription = observable .subscribe( receivedEvents::add, e -> error = e, () -> completed = true ); } Emitter<SimpleReconcilerEvent> getEmitter() { return emitter; } void expectChanges(String... changes) throws InterruptedException { for (String change : changes) { while (true) { SimpleReconcilerEvent event = receivedEvents.poll(30, TimeUnit.SECONDS); if (event == null) { throw new IllegalStateException("no event received in the configured time "); } if (event.getEventType() != SimpleReconcilerEvent.EventType.Checkpoint) { assertThat(event.getMessage()).isEqualTo(change); break; } } } } void expectNoEvents() { assertThat(receivedEvents).isEmpty(); } void drainCheckpoints() { SimpleReconcilerEvent event; while ((event = receivedEvents.peek()) != null) { if (event.getEventType() != SimpleReconcilerEvent.EventType.Checkpoint) { return; } receivedEvents.poll(); } } void unsubscribe() { subscription.unsubscribe(); } void expectStopped() { assertThat(error).isNotNull(); assertThat(error.getMessage()).isEqualTo("Reconciler framework stream closed"); } } }
594
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/framework/reconciler
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/framework/reconciler/internal/SimpleModelUpdateAction.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.reconciler.internal; import java.util.Optional; import com.google.common.base.Preconditions; import com.netflix.titus.common.framework.reconciler.EntityHolder; import com.netflix.titus.common.framework.reconciler.ModelAction; import com.netflix.titus.common.util.tuple.Pair; /** */ public class SimpleModelUpdateAction implements ModelAction { private final EntityHolder entityHolder; private final boolean isRoot; public SimpleModelUpdateAction(EntityHolder entityHolder, boolean isRoot) { Preconditions.checkArgument(entityHolder.getChildren().isEmpty(), "EntryHolder with no children expected"); this.entityHolder = entityHolder; this.isRoot = isRoot; } public EntityHolder getEntityHolder() { return entityHolder; } public boolean isRoot() { return isRoot; } @Override public Optional<Pair<EntityHolder, EntityHolder>> apply(EntityHolder rootHolder) { if (isRoot) { EntityHolder newRoot = rootHolder.setEntity(entityHolder.getEntity()); return Optional.of(Pair.of(newRoot, newRoot)); } EntityHolder newRoot = rootHolder.addChild(entityHolder); return Optional.of(Pair.of(newRoot, entityHolder)); } }
595
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/framework/reconciler
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/framework/reconciler/internal/SimpleReconcilerEvent.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.reconciler.internal; import java.util.Optional; /** * */ public class SimpleReconcilerEvent { enum EventType { Checkpoint, ChangeRequest, Changed, ChangeError, ModelInitial, ModelUpdated, ModelUpdateError } private final long timestamp; private final EventType eventType; private final String message; private final Optional<Throwable> error; public SimpleReconcilerEvent(EventType eventType, String message, Optional<Throwable> error) { this.eventType = eventType; this.message = message; this.error = error; this.timestamp = System.currentTimeMillis(); } public EventType getEventType() { return eventType; } public String getMessage() { return message; } public Optional<Throwable> getError() { return error; } public long getTimestamp() { return timestamp; } @Override public String toString() { return "SimpleReconcilerEvent{" + "timestamp=" + timestamp + ", eventType=" + eventType + ", message='" + message + '\'' + error.map(e -> ", error=" + e.getMessage() + '\'').orElse("") + '}'; } public static SimpleReconcilerEvent newChange(String changedValue) { return new SimpleReconcilerEvent(EventType.Changed, changedValue, Optional.empty()); } }
596
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/framework/reconciler
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/framework/reconciler/internal/DefaultReconciliationFrameworkTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.reconciler.internal; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.TimeUnit; import java.util.function.Function; import com.google.common.collect.ImmutableMap; import com.netflix.spectator.api.DefaultRegistry; import com.netflix.titus.common.framework.reconciler.ChangeAction; import com.netflix.titus.common.framework.reconciler.EntityHolder; import com.netflix.titus.common.framework.reconciler.ModelActionHolder; import com.netflix.titus.common.framework.reconciler.MultiEngineChangeAction; import com.netflix.titus.common.framework.reconciler.ReconciliationEngine; import com.netflix.titus.common.framework.reconciler.internal.SimpleReconcilerEvent.EventType; import com.netflix.titus.common.util.ExceptionExt; import com.netflix.titus.testkit.rx.ExtTestSubscriber; import org.junit.After; import org.junit.Before; import org.junit.Test; import rx.Observable; import rx.observers.AssertableSubscriber; import rx.schedulers.Schedulers; import rx.schedulers.TestScheduler; import rx.subjects.PublishSubject; import static com.jayway.awaitility.Awaitility.await; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class DefaultReconciliationFrameworkTest { private static final long IDLE_TIMEOUT_MS = 100; private static final long ACTIVE_TIMEOUT_MS = 20; private static final long CHECKPOINT_INTERVAL_MS = 10; private static final int STOP_TIMEOUT_MS = 1_000; private final TestScheduler testScheduler = Schedulers.test(); private final Function<EntityHolder, InternalReconciliationEngine<SimpleReconcilerEvent>> engineFactory = mock(Function.class); private final InternalReconciliationEngine engine1 = mock(InternalReconciliationEngine.class); private final InternalReconciliationEngine engine2 = mock(InternalReconciliationEngine.class); private final PublishSubject<SimpleReconcilerEvent> engine1Events = PublishSubject.create(); private final PublishSubject<SimpleReconcilerEvent> engine2Events = PublishSubject.create(); private final Map<Object, Comparator<EntityHolder>> indexComparators = ImmutableMap.<Object, Comparator<EntityHolder>>builder() .put("ascending", Comparator.comparing(EntityHolder::getEntity)) .put("descending", Comparator.<EntityHolder, String>comparing(EntityHolder::getEntity).reversed()) .build(); private final DefaultReconciliationFramework<SimpleReconcilerEvent> framework = new DefaultReconciliationFramework<>( Collections.emptyList(), engineFactory, IDLE_TIMEOUT_MS, ACTIVE_TIMEOUT_MS, CHECKPOINT_INTERVAL_MS, indexComparators, new SimpleReconcilerEventFactory(), new DefaultRegistry(), Optional.of(testScheduler) ); @Before public void setUp() { framework.start(); when(engineFactory.apply(any())).thenReturn(engine1, engine2); when(engine1.triggerActions()).thenReturn(true); when(engine1.getReferenceView()).thenReturn(EntityHolder.newRoot("myRoot1", "myEntity1")); when(engine1.events()).thenReturn(engine1Events.asObservable()); when(engine1.changeReferenceModel(any())).thenAnswer(invocation -> { ChangeAction changeAction = invocation.getArgument(0); return changeAction.apply().ignoreElements().cast(Void.class); }); when(engine2.triggerActions()).thenReturn(true); when(engine2.getReferenceView()).thenReturn(EntityHolder.newRoot("myRoot2", "myEntity2")); when(engine2.events()).thenReturn(engine2Events.asObservable()); when(engine2.changeReferenceModel(any())).thenAnswer(invocation -> { ChangeAction changeAction = invocation.getArgument(0); return changeAction.apply().ignoreElements().cast(Void.class); }); } @After public void tearDown() { framework.stop(STOP_TIMEOUT_MS); } @Test public void testBootstrapEngineInitialization() { InternalReconciliationEngine<SimpleReconcilerEvent> bootstrapEngine = mock(InternalReconciliationEngine.class); PublishSubject<SimpleReconcilerEvent> eventSubject = PublishSubject.create(); when(bootstrapEngine.events()).thenReturn(eventSubject); when(bootstrapEngine.triggerActions()).thenReturn(true); when(bootstrapEngine.getReferenceView()).thenReturn(EntityHolder.newRoot("myRoot1", "myEntity1")); DefaultReconciliationFramework<SimpleReconcilerEvent> framework = new DefaultReconciliationFramework<>( Collections.singletonList(bootstrapEngine), engineFactory, IDLE_TIMEOUT_MS, ACTIVE_TIMEOUT_MS, CHECKPOINT_INTERVAL_MS, indexComparators, new SimpleReconcilerEventFactory(), new DefaultRegistry(), Optional.of(testScheduler) ); framework.start(); AssertableSubscriber<SimpleReconcilerEvent> eventSubscriber = framework.events().test(); eventSubject.onNext(new SimpleReconcilerEvent(EventType.Changed, "test", Optional.empty())); await().timeout(30, TimeUnit.SECONDS).until(() -> assertThat(eventSubscriber.getValueCount()).isGreaterThanOrEqualTo(1)); } @Test public void testEngineAddRemove() { ExtTestSubscriber<ReconciliationEngine> addSubscriber = new ExtTestSubscriber<>(); framework.newEngine(EntityHolder.newRoot("myRoot1", "myEntity")).subscribe( next -> { // When subscriber gets notified, the model must be already updated assertThat(framework.findEngineByRootId("myRoot1")).isPresent(); addSubscriber.onNext(next); }, addSubscriber::onError, addSubscriber::onCompleted ); testScheduler.triggerActions(); InternalReconciliationEngine engine = (InternalReconciliationEngine) addSubscriber.takeNext(); verify(engine, times(1)).emitEvents(); verify(engine, times(1)).closeFinishedTransactions(); verify(engine, times(1)).triggerActions(); // Model updates are performed only on the second iteration testScheduler.advanceTimeBy(ACTIVE_TIMEOUT_MS, TimeUnit.MILLISECONDS); verify(engine, times(1)).applyModelUpdates(); // Now remove the engine ExtTestSubscriber<Void> removeSubscriber = new ExtTestSubscriber<>(); framework.removeEngine(engine).subscribe( () -> { // When subscriber gets notified, the model must be already updated assertThat(framework.findEngineByRootId("myRoot1")).isNotPresent(); addSubscriber.onCompleted(); }, removeSubscriber::onError ); testScheduler.advanceTimeBy(IDLE_TIMEOUT_MS, TimeUnit.MILLISECONDS); verify(engine, times(1)).triggerActions(); } @Test public void testMultiEngineChangeAction() { EntityHolder root1 = EntityHolder.newRoot("myRoot1", "myEntity1"); EntityHolder root2 = EntityHolder.newRoot("myRoot2", "myEntity2"); framework.newEngine(root1).subscribe(); framework.newEngine(root2).subscribe(); testScheduler.triggerActions(); MultiEngineChangeAction multiEngineChangeAction = () -> Observable.just(ImmutableMap.of( "myRoot1", ModelActionHolder.allModels(new SimpleModelUpdateAction(EntityHolder.newRoot("myRoot1", "myEntity1#v2"), true)), "myRoot2", ModelActionHolder.allModels(new SimpleModelUpdateAction(EntityHolder.newRoot("myRoot2", "myEntity2#v2"), true)) )); Map<String, List<ModelActionHolder>> holders = new HashMap<>(); Observable<Void> multiChangeObservable = framework.changeReferenceModel( multiEngineChangeAction, (id, modelUpdates) -> { ChangeAction changeAction = () -> modelUpdates.doOnNext(next -> holders.put(id, next)); return changeAction; }, "myRoot1", "myRoot2" ); verify(engine1, times(0)).changeReferenceModel(any()); verify(engine2, times(0)).changeReferenceModel(any()); ExtTestSubscriber<Void> multiChangeSubscriber = new ExtTestSubscriber<>(); multiChangeObservable.subscribe(multiChangeSubscriber); assertThat(multiChangeSubscriber.isUnsubscribed()).isTrue(); verify(engine1, times(1)).changeReferenceModel(any()); verify(engine2, times(1)).changeReferenceModel(any()); // one action per view (Running, Store, Reference) assertThat(holders.get("myRoot1")).hasSize(3); SimpleModelUpdateAction modelAction1 = (SimpleModelUpdateAction) holders.get("myRoot1").get(0).getAction(); assertThat((String) modelAction1.getEntityHolder().getEntity()).isEqualTo("myEntity1#v2"); // one action per view (Running, Store, Reference) assertThat(holders.get("myRoot2")).hasSize(3); SimpleModelUpdateAction modelAction2 = (SimpleModelUpdateAction) holders.get("myRoot2").get(0).getAction(); assertThat((String) modelAction2.getEntityHolder().getEntity()).isEqualTo("myEntity2#v2"); } @Test public void testMultiEngineChangeActionWithInvalidEngineId() { EntityHolder root1 = EntityHolder.newRoot("myRoot1", "myEntity1"); framework.newEngine(root1).subscribe(); testScheduler.triggerActions(); Observable<Void> multiChangeObservable = framework.changeReferenceModel( // Keep anonymous class instead of lambda for readability new MultiEngineChangeAction() { @Override public Observable<Map<String, List<ModelActionHolder>>> apply() { return Observable.error(new IllegalStateException("invocation not expected")); } }, // Keep anonymous class instead of lambda for readability (id, modelUpdates) -> new ChangeAction() { @Override public Observable<List<ModelActionHolder>> apply() { return Observable.error(new IllegalStateException("invocation not expected")); } }, "myRoot1", "badRootId" ); ExtTestSubscriber<Void> multiChangeSubscriber = new ExtTestSubscriber<>(); multiChangeObservable.subscribe(multiChangeSubscriber); assertThat(multiChangeSubscriber.isError()).isTrue(); assertThat(multiChangeSubscriber.getError().getMessage()).contains("badRootId"); } @Test public void testFailingMultiEngineChangeAction() { EntityHolder root1 = EntityHolder.newRoot("myRoot1", "myEntity1"); EntityHolder root2 = EntityHolder.newRoot("myRoot2", "myEntity2"); framework.newEngine(root1).subscribe(); framework.newEngine(root2).subscribe(); testScheduler.triggerActions(); Observable<Void> multiChangeObservable = framework.changeReferenceModel( // Keep anonymous class instead of lambda for readability new MultiEngineChangeAction() { @Override public Observable<Map<String, List<ModelActionHolder>>> apply() { return Observable.error(new RuntimeException("simulated error")); } }, // Keep anonymous class instead of lambda for readability (id, modelUpdates) -> new ChangeAction() { @Override public Observable<List<ModelActionHolder>> apply() { return modelUpdates; } }, "myRoot1", "myRoot2" ); ExtTestSubscriber<Void> multiChangeSubscriber = new ExtTestSubscriber<>(); multiChangeObservable.subscribe(multiChangeSubscriber); assertThat(multiChangeSubscriber.isError()).isTrue(); String errorMessage = ExceptionExt.toMessageChain(multiChangeSubscriber.getError()); assertThat(errorMessage).contains("simulated error"); } @Test public void testIndexes() { framework.newEngine(EntityHolder.newRoot("myRoot1", "myEntity1")).subscribe(); framework.newEngine(EntityHolder.newRoot("myRoot2", "myEntity2")).subscribe(); testScheduler.triggerActions(); assertThat(framework.orderedView("ascending").stream().map(EntityHolder::getEntity)).containsExactly("myEntity1", "myEntity2"); assertThat(framework.orderedView("descending").stream().map(EntityHolder::getEntity)).containsExactly("myEntity2", "myEntity1"); } @Test public void testEventsPublishing() throws Exception { framework.newEngine(EntityHolder.newRoot("myRoot1", "myEntity1")).subscribe(); framework.newEngine(EntityHolder.newRoot("myRoot2", "myEntity2")).subscribe(); testScheduler.triggerActions(); ExtTestSubscriber<SimpleReconcilerEvent> eventSubscriber = new ExtTestSubscriber<>(); framework.events().subscribe(eventSubscriber); engine1Events.onNext(newEvent("event1")); expectEvent(eventSubscriber, "event1"); engine1Events.onCompleted(); assertThat(eventSubscriber.isUnsubscribed()).isFalse(); engine2Events.onNext(newEvent("event2")); expectEvent(eventSubscriber, "event2"); } private void expectEvent(ExtTestSubscriber<SimpleReconcilerEvent> eventSubscriber, String message) throws InterruptedException { while (true) { SimpleReconcilerEvent event = eventSubscriber.takeNext(30, TimeUnit.SECONDS); if (event.getEventType() != EventType.Checkpoint) { assertThat(event.getMessage()).isEqualTo(message); return; } } } private SimpleReconcilerEvent newEvent(String message) { return new SimpleReconcilerEvent(EventType.Changed, message, Optional.empty()); } }
597
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/framework/reconciler
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/framework/reconciler/internal/DefaultReconciliationEngineTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.reconciler.internal; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Queue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import com.google.common.collect.ImmutableMap; import com.netflix.titus.common.framework.reconciler.ChangeAction; import com.netflix.titus.common.framework.reconciler.EntityHolder; import com.netflix.titus.common.framework.reconciler.ModelAction; import com.netflix.titus.common.framework.reconciler.ModelActionHolder; import com.netflix.titus.common.framework.reconciler.ReconciliationEngine; import com.netflix.titus.common.framework.reconciler.internal.SimpleReconcilerEvent.EventType; import com.netflix.titus.common.runtime.TitusRuntimes; import com.netflix.titus.common.util.tuple.Pair; import com.netflix.titus.testkit.rx.ExtTestSubscriber; import org.junit.Before; import org.junit.Test; import rx.Observable; import rx.Subscription; import rx.schedulers.Schedulers; import rx.schedulers.TestScheduler; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; public class DefaultReconciliationEngineTest { private final TestScheduler testScheduler = Schedulers.test(); private final Map<Object, Comparator<EntityHolder>> indexComparators = ImmutableMap.<Object, Comparator<EntityHolder>>builder() .put("ascending", Comparator.comparing(EntityHolder::getEntity)) .put("descending", Comparator.<EntityHolder, String>comparing(EntityHolder::getEntity).reversed()) .build(); private final DefaultReconciliationEngine<SimpleReconcilerEvent> engine = new DefaultReconciliationEngine<>( EntityHolder.newRoot("myRoot", "rootInitial"), true, this::difference, indexComparators, new SimpleReconcilerEventFactory(), changeAction -> Collections.emptyList(), event -> Collections.emptyList(), TitusRuntimes.test(testScheduler) ); private final ExtTestSubscriber<SimpleReconcilerEvent> eventSubscriber = new ExtTestSubscriber<>(); private final Queue<List<ChangeAction>> runtimeReconcileActions = new LinkedBlockingQueue<>(); @Before public void setUp() { engine.events().cast(SimpleReconcilerEvent.class).subscribe(eventSubscriber); } @Test public void testReferenceModelChange() { ExtTestSubscriber<Void> testSubscriber = new ExtTestSubscriber<>(); engine.changeReferenceModel(new SlowChangeAction()).subscribe(testSubscriber); // Trigger change event assertThat(engine.applyModelUpdates()).isFalse(); engine.emitEvents(); assertThat(engine.triggerActions()).isTrue(); testSubscriber.assertOpen(); assertThat(eventSubscriber.takeNext().getEventType()).isEqualTo(EventType.ModelInitial); assertThat(eventSubscriber.takeNext().getEventType()).isEqualTo(EventType.ChangeRequest); // Move time, and verify that model is updated testScheduler.advanceTimeBy(1, TimeUnit.SECONDS); assertThat(engine.applyModelUpdates()).isTrue(); engine.emitEvents(); engine.closeFinishedTransactions(); assertThat(engine.triggerActions()).isFalse(); assertThat(eventSubscriber.takeNext().getEventType()).isEqualTo(EventType.ModelUpdated); assertThat(eventSubscriber.takeNext().getEventType()).isEqualTo(EventType.Changed); assertThat(testSubscriber.isUnsubscribed()).isTrue(); } @Test public void testChildAddRemove() { addChild("child1"); assertThat(engine.getReferenceView().getId()).isEqualTo("myRoot"); assertThat(engine.getReferenceView().getChildren()).hasSize(1); removeChild("child1"); assertThat(engine.getReferenceView().getId()).isEqualTo("myRoot"); assertThat(engine.getReferenceView().getChildren()).isEmpty(); } @Test public void testReferenceModelChangeFailure() { RuntimeException failure = new RuntimeException("simulated ChangeAction error"); testFailingChangeAction(() -> Observable.error(failure), failure); } @Test public void testReferenceModelChangeWithEscapedException() { RuntimeException failure = new RuntimeException("Escaped ChangeAction exception"); testFailingChangeAction(() -> { throw failure; }, failure); } @Test public void testReferenceModelChangeFailureDuringModelUpdate() { RuntimeException failure = new RuntimeException("ModelUpdate exception"); testFailingChangeAction(() -> Observable.just(singletonList(ModelActionHolder.reference(rootHolder -> { throw failure; }))), failure); } private void testFailingChangeAction(ChangeAction failingChangeAction, Throwable expectedError) { ExtTestSubscriber<Void> testSubscriber = new ExtTestSubscriber<>(); engine.changeReferenceModel(failingChangeAction).subscribe(testSubscriber); // Consume initial events engine.emitEvents(); assertThat(eventSubscriber.takeNext().getEventType()).isEqualTo(EventType.ModelInitial); assertThat(eventSubscriber.takeNext().getEventType()).isEqualTo(EventType.ChangeRequest); // Trigger failing action engine.triggerActions(); engine.applyModelUpdates(); engine.emitEvents(); SimpleReconcilerEvent changeErrorEvent = eventSubscriber.takeNext(); assertThat(changeErrorEvent.getEventType()).isIn(EventType.ChangeError, EventType.ModelUpdateError); assertThat(changeErrorEvent.getError()).contains(expectedError); assertThat(eventSubscriber.takeNext()).isNull(); assertThat(engine.closeFinishedTransactions()).isTrue(); testSubscriber.assertOnError(expectedError); } @Test public void testChangeActionSubscriberThrowingExceptionInOnCompleted() { engine.changeReferenceModel(new RootChangeAction("rootUpdate")).subscribe( next -> { }, e -> { }, () -> { throw new RuntimeException("Simulated event onComplete error"); } ); engine.emitEvents(); assertThat(engine.triggerActions()).isTrue(); assertThat(engine.applyModelUpdates()).isTrue(); engine.emitEvents(); assertThat(engine.closeFinishedTransactions()).isTrue(); } @Test public void testChangeActionSubscriberThrowingExceptionInOnError() { engine.changeReferenceModel(() -> Observable.error(new RuntimeException("Change action error"))).subscribe( next -> { }, e -> { throw new RuntimeException("Simulated event onError error"); }, () -> { } ); engine.emitEvents(); assertThat(engine.triggerActions()).isTrue(); assertThat(engine.applyModelUpdates()).isFalse(); engine.emitEvents(); assertThat(engine.closeFinishedTransactions()).isTrue(); } @Test public void testParallelExecutionOfNonOverlappingTasks() { addChild("child1"); addChild("child2"); ExtTestSubscriber<Void> child1Subscriber = new ExtTestSubscriber<>(); ExtTestSubscriber<Void> child2Subscriber = new ExtTestSubscriber<>(); engine.changeReferenceModel(new UpdateChildAction("child1", "update1"), "child1").subscribe(child1Subscriber); engine.changeReferenceModel(new UpdateChildAction("child2", "update2"), "child2").subscribe(child2Subscriber); engine.triggerActions(); assertThat(engine.applyModelUpdates()).isTrue(); engine.emitEvents(); assertThat(engine.closeFinishedTransactions()).isTrue(); child1Subscriber.assertOnCompleted(); child2Subscriber.assertOnCompleted(); assertThat(engine.getReferenceView().findChildById("child1").get().<String>getEntity()).isEqualTo("update1"); assertThat(engine.getReferenceView().findChildById("child2").get().<String>getEntity()).isEqualTo("update2"); } @Test public void testParallelExecutionOfNonOverlappingTasksWithOneTaskFailing() { addChild("child1"); addChild("child2"); ExtTestSubscriber<Void> child1Subscriber = new ExtTestSubscriber<>(); ExtTestSubscriber<Void> child2Subscriber = new ExtTestSubscriber<>(); engine.changeReferenceModel(new UpdateChildAction("child1", "update1"), "child1").subscribe(child1Subscriber); RuntimeException failure = new RuntimeException("ModelUpdate exception"); engine.changeReferenceModel(() -> { throw failure; }, "child2").subscribe(child2Subscriber); engine.triggerActions(); assertThat(engine.applyModelUpdates()).isTrue(); engine.emitEvents(); assertThat(engine.closeFinishedTransactions()).isTrue(); child1Subscriber.assertOnCompleted(); child2Subscriber.assertOnError(failure); assertThat(engine.getReferenceView().findChildById("child1").get().<String>getEntity()).isEqualTo("update1"); assertThat(engine.getReferenceView().findChildById("child2").get().<String>getEntity()).isEqualTo("child2"); } @Test public void testOverlappingTasksAreExecutedSequentially() { addChild("child1"); addChild("child2"); ExtTestSubscriber<Void> child1Subscriber = new ExtTestSubscriber<>(); ExtTestSubscriber<Void> rootSubscriber = new ExtTestSubscriber<>(); ExtTestSubscriber<Void> child2Subscriber = new ExtTestSubscriber<>(); engine.changeReferenceModel(new UpdateChildAction("child1", "update1"), "child1").subscribe(child1Subscriber); engine.changeReferenceModel(new RootChangeAction("rootUpdate")).subscribe(rootSubscriber); engine.changeReferenceModel(new UpdateChildAction("child2", "update2"), "child2").subscribe(child2Subscriber); // Child 1 engine.triggerActions(); assertThat(engine.applyModelUpdates()).isTrue(); engine.emitEvents(); assertThat(engine.closeFinishedTransactions()).isTrue(); child1Subscriber.assertOnCompleted(); rootSubscriber.assertOpen(); assertThat(engine.getReferenceView().findChildById("child1").get().<String>getEntity()).isEqualTo("update1"); assertThat(engine.getReferenceView().<String>getEntity()).isEqualTo("rootInitial"); assertThat(engine.getReferenceView().findChildById("child2").get().<String>getEntity()).isEqualTo("child2"); // Root engine.triggerActions(); assertThat(engine.applyModelUpdates()).isTrue(); engine.emitEvents(); assertThat(engine.closeFinishedTransactions()).isTrue(); rootSubscriber.assertOnCompleted(); child2Subscriber.assertOpen(); assertThat(engine.getReferenceView().<String>getEntity()).isEqualTo("rootUpdate"); assertThat(engine.getReferenceView().findChildById("child2").get().<String>getEntity()).isEqualTo("child2"); // Child 2 engine.triggerActions(); assertThat(engine.applyModelUpdates()).isTrue(); engine.emitEvents(); assertThat(engine.closeFinishedTransactions()).isTrue(); child2Subscriber.assertOnCompleted(); assertThat(engine.getReferenceView().findChildById("child2").get().<String>getEntity()).isEqualTo("update2"); } @Test public void testReconciliationActions() { Subscription setupSubscription = engine.changeReferenceModel(new RootChangeAction("rootValue")).subscribe(); assertThat(engine.applyModelUpdates()).isFalse(); assertThat(engine.triggerActions()).isTrue(); runtimeReconcileActions.add(singletonList(new SlowChangeAction())); // Complete first change action assertThat(engine.applyModelUpdates()).isTrue(); engine.emitEvents(); engine.closeFinishedTransactions(); assertThat(setupSubscription.isUnsubscribed()).isTrue(); // Create the reconciler action assertThat(engine.triggerActions()).isTrue(); testScheduler.advanceTimeBy(1, TimeUnit.SECONDS); assertThat(engine.applyModelUpdates()).isTrue(); engine.emitEvents(); engine.closeFinishedTransactions(); assertThat(engine.triggerActions()).isFalse(); List<EventType> emittedEvents = eventSubscriber.takeNext(7).stream().map(SimpleReconcilerEvent::getEventType).collect(Collectors.toList()); assertThat(emittedEvents).contains( // From root setup EventType.ChangeRequest, EventType.ModelUpdated, EventType.ModelUpdated, EventType.Changed, // From reconciler EventType.ChangeRequest, EventType.ModelUpdated, EventType.Changed ); } @Test public void testChangeActionCancellation() { SlowChangeAction action = new SlowChangeAction(); Subscription subscription = engine.changeReferenceModel(action).subscribe(); engine.triggerActions(); assertThat(action.unsubscribed).isFalse(); subscription.unsubscribe(); assertThat(action.unsubscribed).isTrue(); } @Test public void testIndexes() { addChild("child1"); addChild("child2"); assertThat(engine.orderedView("ascending").stream().map(EntityHolder::getEntity)).containsExactly("child1", "child2"); assertThat(engine.orderedView("descending").stream().map(EntityHolder::getEntity)).containsExactly("child2", "child1"); } @Test public void testEventStreamConsumersThrowingException() { RuntimeException failure = new RuntimeException("Simulated event handler error"); engine.events().subscribe( event -> { throw failure; }, e -> assertThat(e).isEqualTo(failure)); ExtTestSubscriber<Void> rootSubscriber = new ExtTestSubscriber<>(); engine.changeReferenceModel(new RootChangeAction("rootUpdate")).subscribe(rootSubscriber); engine.emitEvents(); assertThat(engine.triggerActions()).isTrue(); assertThat(engine.applyModelUpdates()).isTrue(); engine.emitEvents(); assertThat(engine.closeFinishedTransactions()).isTrue(); } private void addChild(String childId) { engine.changeReferenceModel(new AddChildAction(childId)).subscribe(); engine.triggerActions(); assertThat(engine.applyModelUpdates()).isTrue(); engine.emitEvents(); engine.closeFinishedTransactions(); } private void removeChild(String childId) { engine.changeReferenceModel(new RemoveChildAction(childId)).subscribe(); engine.triggerActions(); assertThat(engine.applyModelUpdates()).isTrue(); engine.emitEvents(); engine.closeFinishedTransactions(); } private List<ChangeAction> difference(ReconciliationEngine<SimpleReconcilerEvent> engine) { List<ChangeAction> next = runtimeReconcileActions.poll(); return next == null ? Collections.emptyList() : next; } class RootChangeAction implements ChangeAction { private final String rootValue; RootChangeAction(String rootValue) { this.rootValue = rootValue; } @Override public Observable<List<ModelActionHolder>> apply() { return Observable.just(ModelActionHolder.referenceAndRunning(new SimpleModelUpdateAction(EntityHolder.newRoot("root#0", rootValue), true))); } } class SlowChangeAction implements ChangeAction { private volatile boolean unsubscribed; @Override public Observable<List<ModelActionHolder>> apply() { return Observable.timer(1, TimeUnit.SECONDS, testScheduler).map(tick -> { ModelAction updateAction = new SimpleModelUpdateAction(EntityHolder.newRoot("root#0", "ROOT"), true); return ModelActionHolder.referenceList(updateAction); } ).doOnUnsubscribe(() -> unsubscribed = true); } } class AddChildAction implements ChangeAction { private final String childId; AddChildAction(String childId) { this.childId = childId; } @Override public Observable<List<ModelActionHolder>> apply() { SimpleModelUpdateAction updateAction = new SimpleModelUpdateAction(EntityHolder.newRoot(childId, childId), false); return Observable.just(ModelActionHolder.referenceList(updateAction)); } } class RemoveChildAction implements ChangeAction { private final String childId; RemoveChildAction(String childId) { this.childId = childId; } @Override public Observable<List<ModelActionHolder>> apply() { ModelAction updateAction = rootHolder -> { Pair<EntityHolder, Optional<EntityHolder>> result = rootHolder.removeChild(childId); return result.getRight().map(removed -> Pair.of(result.getLeft(), removed)); }; return Observable.just(ModelActionHolder.referenceList(updateAction)); } } class UpdateChildAction implements ChangeAction { private final String childId; private final String value; UpdateChildAction(String childId, String value) { this.childId = childId; this.value = value; } @Override public Observable<List<ModelActionHolder>> apply() { SimpleModelUpdateAction updateAction = new SimpleModelUpdateAction(EntityHolder.newRoot(childId, value), false); return Observable.just(ModelActionHolder.referenceList(updateAction)); } } }
598
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/network/http/internal
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/network/http/internal/okhttp/OkHttpClientTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.network.http.internal.okhttp; import java.io.InputStream; import java.io.InputStreamReader; import java.net.InetAddress; import java.util.Collections; import java.util.concurrent.TimeUnit; import com.google.common.base.Charsets; import com.google.common.io.CharStreams; import com.netflix.titus.common.network.http.EndpointResolver; import com.netflix.titus.common.network.http.HttpClient; import com.netflix.titus.common.network.http.Request; import com.netflix.titus.common.network.http.RequestBody; import com.netflix.titus.common.network.http.Response; import com.netflix.titus.common.network.http.StatusCode; import com.netflix.titus.common.network.http.internal.RoundRobinEndpointResolver; import okhttp3.Interceptor; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import okhttp3.mockwebserver.RecordedRequest; import okhttp3.tls.HandshakeCertificates; import okhttp3.tls.HeldCertificate; import org.assertj.core.api.Assertions; import org.junit.After; import org.junit.Before; import org.junit.Test; public class OkHttpClientTest { private static final String TEST_REQUEST_BODY = "Test Request Body"; private static final String TEST_RESPONSE_BODY = "Test Response Body"; private MockWebServer server; @Before public void setUp() throws Exception { server = new MockWebServer(); } @After public void tearDown() throws Exception { server.shutdown(); } @Test public void testGet() throws Exception { MockResponse mockResponse = new MockResponse() .setBody(TEST_RESPONSE_BODY) .setResponseCode(StatusCode.OK.getCode()); server.enqueue(mockResponse); HttpClient client = OkHttpClient.newBuilder() .build(); Request request = new Request.Builder() .url(server.url("/").toString()) .get() .build(); Response response = client.execute(request); Assertions.assertThat(response.isSuccessful()).isTrue(); InputStream inputStream = response.getBody().get(InputStream.class); String actualResponseBody = CharStreams.toString(new InputStreamReader(inputStream, Charsets.UTF_8)); Assertions.assertThat(actualResponseBody).isEqualTo(TEST_RESPONSE_BODY); RecordedRequest recordedRequest = server.takeRequest(1, TimeUnit.MILLISECONDS); Assertions.assertThat(recordedRequest).isNotNull(); Assertions.assertThat(recordedRequest.getBodySize()).isLessThanOrEqualTo(0); } @Test public void testPost() throws Exception { MockResponse mockResponse = new MockResponse() .setBody(TEST_RESPONSE_BODY) .setResponseCode(StatusCode.OK.getCode()); server.enqueue(mockResponse); HttpClient client = OkHttpClient.newBuilder() .build(); Request request = new Request.Builder() .url(server.url("/").toString()) .post() .body(RequestBody.create(TEST_REQUEST_BODY)) .build(); Response response = client.execute(request); Assertions.assertThat(response.isSuccessful()).isTrue(); String actualResponseBody = response.getBody().get(String.class); Assertions.assertThat(actualResponseBody).isEqualTo(TEST_RESPONSE_BODY); RecordedRequest recordedRequest = server.takeRequest(1, TimeUnit.MILLISECONDS); Assertions.assertThat(recordedRequest).isNotNull(); String actualRequestBody = recordedRequest.getBody().readUtf8(); Assertions.assertThat(actualRequestBody).isEqualTo(TEST_REQUEST_BODY); } @Test public void testGetWithEndpointResolver() throws Exception { MockResponse mockResponse = new MockResponse() .setBody(TEST_RESPONSE_BODY) .setResponseCode(StatusCode.OK.getCode()); server.enqueue(mockResponse); EndpointResolver roundRobinEndpointResolver = new RoundRobinEndpointResolver(server.url("").toString()); Interceptor endpointResolverInterceptor = new EndpointResolverInterceptor(roundRobinEndpointResolver); HttpClient client = OkHttpClient.newBuilder() .interceptor(endpointResolverInterceptor) .build(); Request request = new Request.Builder() .url("/") .get() .build(); Response response = client.execute(request); Assertions.assertThat(response.isSuccessful()).isTrue(); InputStream inputStream = response.getBody().get(InputStream.class); String actualResponseBody = CharStreams.toString(new InputStreamReader(inputStream, Charsets.UTF_8)); Assertions.assertThat(actualResponseBody).isEqualTo(TEST_RESPONSE_BODY); RecordedRequest recordedRequest = server.takeRequest(1, TimeUnit.MILLISECONDS); Assertions.assertThat(recordedRequest).isNotNull(); Assertions.assertThat(recordedRequest.getBodySize()).isLessThanOrEqualTo(0); } @Test public void testGetWithRetries() throws Exception { MockResponse notAvailableResponse = new MockResponse() .setBody(TEST_RESPONSE_BODY) .setResponseCode(StatusCode.SERVICE_UNAVAILABLE.getCode()); server.enqueue(notAvailableResponse); MockResponse internalErrorResponse = new MockResponse() .setBody(TEST_RESPONSE_BODY) .setResponseCode(StatusCode.INTERNAL_SERVER_ERROR.getCode()); server.enqueue(internalErrorResponse); MockResponse successfulResponse = new MockResponse() .setBody(TEST_RESPONSE_BODY) .setResponseCode(StatusCode.OK.getCode()); server.enqueue(successfulResponse); Interceptor passthroughInterceptor = new PassthroughInterceptor(); Interceptor compositeRetryInterceptor = new CompositeRetryInterceptor(Collections.singletonList(passthroughInterceptor), 3); HttpClient client = OkHttpClient.newBuilder() .interceptor(compositeRetryInterceptor) .build(); Request request = new Request.Builder() .url(server.url("/").toString()) .get() .build(); Response response = client.execute(request); Assertions.assertThat(response.isSuccessful()).isTrue(); InputStream inputStream = response.getBody().get(InputStream.class); String actualResponseBody = CharStreams.toString(new InputStreamReader(inputStream, Charsets.UTF_8)); Assertions.assertThat(actualResponseBody).isEqualTo(TEST_RESPONSE_BODY); server.takeRequest(1, TimeUnit.MILLISECONDS); server.takeRequest(1, TimeUnit.MILLISECONDS); RecordedRequest recordedRequest = server.takeRequest(1, TimeUnit.MILLISECONDS); Assertions.assertThat(recordedRequest).isNotNull(); Assertions.assertThat(recordedRequest.getBodySize()).isLessThanOrEqualTo(0); } @Test public void testPostWithRetriesSendsOnlyOneRequest() throws Exception { MockResponse notAvailableResponse = new MockResponse() .setBody(TEST_RESPONSE_BODY) .setResponseCode(StatusCode.SERVICE_UNAVAILABLE.getCode()); server.enqueue(notAvailableResponse); MockResponse successfulResponse = new MockResponse() .setBody(TEST_RESPONSE_BODY) .setResponseCode(StatusCode.OK.getCode()); server.enqueue(successfulResponse); Interceptor passthroughInterceptor = new PassthroughInterceptor(); Interceptor compositeRetryInterceptor = new CompositeRetryInterceptor(Collections.singletonList(passthroughInterceptor), 3); HttpClient client = OkHttpClient.newBuilder() .interceptor(compositeRetryInterceptor) .build(); Request request = new Request.Builder() .url(server.url("/").toString()) .post() .body(RequestBody.create(TEST_REQUEST_BODY)) .build(); Response response = client.execute(request); Assertions.assertThat(server.getRequestCount()).isEqualTo(1); Assertions.assertThat(response.getStatusCode()).isEqualTo(StatusCode.SERVICE_UNAVAILABLE); Assertions.assertThat(response.getBody().get(String.class)).isEqualTo(TEST_RESPONSE_BODY); } @Test public void testGetWithSslContext() throws Exception { String localhost = InetAddress.getByName("localhost").getCanonicalHostName(); HeldCertificate localhostCertificate = new HeldCertificate.Builder() .addSubjectAlternativeName(localhost) .build(); HandshakeCertificates serverCertificates = new HandshakeCertificates.Builder() .heldCertificate(localhostCertificate) .build(); try(MockWebServer sslServer = new MockWebServer()) { sslServer.useHttps(serverCertificates.sslSocketFactory(), false); String url = sslServer.url("/").toString(); MockResponse mockResponse = new MockResponse() .setBody(TEST_RESPONSE_BODY) .setResponseCode(StatusCode.OK.getCode()); sslServer.enqueue(mockResponse); HandshakeCertificates clientCertificates = new HandshakeCertificates.Builder() .addTrustedCertificate(localhostCertificate.certificate()) .build(); HttpClient client = OkHttpClient.newBuilder() .sslContext(clientCertificates.sslContext()) .trustManager(clientCertificates.trustManager()) .build(); Request request = new Request.Builder() .url(url) .get() .build(); Response response = client.execute(request); Assertions.assertThat(response.isSuccessful()).isTrue(); InputStream inputStream = response.getBody().get(InputStream.class); String actualResponseBody = CharStreams.toString(new InputStreamReader(inputStream, Charsets.UTF_8)); Assertions.assertThat(actualResponseBody).isEqualTo(TEST_RESPONSE_BODY); RecordedRequest recordedRequest = sslServer.takeRequest(1, TimeUnit.MILLISECONDS); Assertions.assertThat(recordedRequest).isNotNull(); Assertions.assertThat(recordedRequest.getBodySize()).isLessThanOrEqualTo(0); } } }
599