/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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 org.apache.shardingsphere.elasticjob.reg.zookeeper;

import lombok.SneakyThrows;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.leader.LeaderSelector;
import org.apache.curator.retry.RetryOneTime;
import org.apache.curator.test.KillSession;
import org.apache.shardingsphere.elasticjob.reg.zookeeper.fixture.EmbedTestingServer;
import org.apache.shardingsphere.elasticjob.reg.base.ElectionCandidate;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

import java.lang.reflect.Field;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;

@RunWith(MockitoJUnitRunner.class)
public class ZookeeperElectionServiceTest {
    
    private static final String HOST_AND_PORT = "localhost:8899";
    
    private static final String ELECTION_PATH = "/election";
    
    @Mock
    private ElectionCandidate electionCandidate;
    
    @BeforeClass
    public static void init() {
        EmbedTestingServer.start();
    }
    
    @Test
    public void assertContend() throws Exception {
        CuratorFramework client = CuratorFrameworkFactory.newClient(EmbedTestingServer.getConnectionString(), new RetryOneTime(2000));
        client.start();
        client.blockUntilConnected();
        ZookeeperElectionService service = new ZookeeperElectionService(HOST_AND_PORT, client, ELECTION_PATH, electionCandidate);
        service.start();
        ElectionCandidate anotherElectionCandidate = mock(ElectionCandidate.class);
        CuratorFramework anotherClient = CuratorFrameworkFactory.newClient(EmbedTestingServer.getConnectionString(), new RetryOneTime(2000));
        ZookeeperElectionService anotherService = new ZookeeperElectionService("ANOTHER_CLIENT:8899", anotherClient, ELECTION_PATH, anotherElectionCandidate);
        anotherClient.start();
        anotherClient.blockUntilConnected();
        anotherService.start();
        KillSession.kill(client.getZookeeperClient().getZooKeeper());
        service.stop();
        blockUtilHasLeadership(anotherService);
        verify(anotherElectionCandidate).startLeadership();
    }
    
    @SneakyThrows
    private void blockUtilHasLeadership(final Object obj) {
        Field field = ZookeeperElectionService.class.getDeclaredField("leaderSelector");
        field.setAccessible(true);
        while (!((LeaderSelector) field.get(obj)).hasLeadership()) {
            Thread.sleep(100);
        }
    }
}

@@ -1505,16 +1505,96 @@
 t.Field;
+%0Aimport java.util.concurrent.CountDownLatch;%0Aimport java.util.function.Supplier;
 %0A%0Aimport
@@ -1668,16 +1668,63 @@
 .verify;
+%0Aimport static org.mockito.Mockito.atLeastOnce;
 %0A%0A@RunWi
@@ -3116,39 +3116,240 @@
 ockU
+n
 til
-HasLeadership(anotherService
+Condition(() -%3E hasLeadership(anotherService));%0A        ((CountDownLatch) getFieldValue(anotherService, %22leaderLatch%22)).countDown();%0A        blockUntilCondition(() -%3E !hasLeadership(anotherService));%0A        anotherService.stop(
 );%0A 
@@ -3386,16 +3386,31 @@
 andidate
+, atLeastOnce()
 ).startL
@@ -3418,24 +3418,98 @@
 adership();%0A
+        verify(anotherElectionCandidate, atLeastOnce()).stopLeadership();%0A
     %7D%0A    %0A 
@@ -3552,278 +3552,604 @@
 ockU
+n
 til
-HasLeadership(final Object obj) %7B%0A        Field field = ZookeeperElectionService.class.getDeclaredField(%22leaderSelector%22
+Condition(final Supplier%3CBoolean%3E condition) %7B%0A        while (!condition.get()) %7B%0A            Thread.sleep(100);%0A        %7D%0A    %7D%0A%0A    @SneakyThrows%0A    private boolean hasLeadership(final ZookeeperElectionService zookeeperElectionService) %7B%0A        return ((LeaderSelector) getFieldValue(zookeeperElectionService, %22leaderSelector%22)).hasLeadership(
 );%0A    
+%7D%0A%0A
     
-field.setAccessible(true);%0A        while (!((LeaderSelector) field.get(obj)).hasLeadership()) %7B%0A            Thread.sleep(100);%0A        %7D
+@SneakyThrows%0A    private Object getFieldValue(final Object target, final String fieldName) %7B%0A        Field field = target.getClass().getDeclaredField(fieldName);%0A        field.setAccessible(true);%0A        return field.get(target);
 %0A   

Fix ZookeeperElectionServiceTest.assertContend failed for travis-ci (#1665)