output
stringlengths 7
516k
| instruction
stringclasses 1
value | input
stringlengths 6
884k
|
---|---|---|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.config.job;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.fixture.CloudJsonConstants;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.producer.ProducerManager;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.state.ready.ReadyService;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentMatchers;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.unitils.util.ReflectionUtils;
import java.util.Collections;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@RunWith(MockitoJUnitRunner.class)
public final class CloudJobConfigurationListenerTest {
@Mock
private ProducerManager producerManager;
@Mock
private ReadyService readyService;
@InjectMocks
private CloudJobConfigurationListener cloudJobConfigurationListener;
@Before
public void setUp() throws NoSuchFieldException {
ReflectionUtils.setFieldValue(cloudJobConfigurationListener, "producerManager", producerManager);
ReflectionUtils.setFieldValue(cloudJobConfigurationListener, "readyService", readyService);
}
@Test
public void assertChildEventWhenDataIsNull() throws Exception {
cloudJobConfigurationListener.childEvent(null, new TreeCacheEvent(TreeCacheEvent.Type.NODE_ADDED, null));
verify(producerManager, times(0)).schedule(ArgumentMatchers.<CloudJobConfiguration>any());
verify(producerManager, times(0)).reschedule(ArgumentMatchers.<String>any());
verify(producerManager, times(0)).unschedule(ArgumentMatchers.<String>any());
}
@Test
public void assertChildEventWhenIsNotConfigPath() throws Exception {
cloudJobConfigurationListener.childEvent(null, new TreeCacheEvent(TreeCacheEvent.Type.NODE_UPDATED, new ChildData("/other/test_job", null, "".getBytes())));
verify(producerManager, times(0)).schedule(ArgumentMatchers.<CloudJobConfiguration>any());
verify(producerManager, times(0)).reschedule(ArgumentMatchers.<String>any());
verify(producerManager, times(0)).unschedule(ArgumentMatchers.<String>any());
}
@Test
public void assertChildEventWhenIsRootConfigPath() throws Exception {
cloudJobConfigurationListener.childEvent(null, new TreeCacheEvent(TreeCacheEvent.Type.NODE_REMOVED, new ChildData("/config/job", null, "".getBytes())));
verify(producerManager, times(0)).schedule(ArgumentMatchers.<CloudJobConfiguration>any());
verify(producerManager, times(0)).reschedule(ArgumentMatchers.<String>any());
verify(producerManager, times(0)).unschedule(ArgumentMatchers.<String>any());
}
@Test
public void assertChildEventWhenStateIsAddAndIsConfigPathAndInvalidData() throws Exception {
cloudJobConfigurationListener.childEvent(null, new TreeCacheEvent(TreeCacheEvent.Type.NODE_ADDED, new ChildData("/config/job/test_job", null, "".getBytes())));
verify(producerManager, times(0)).schedule(ArgumentMatchers.<CloudJobConfiguration>any());
verify(producerManager, times(0)).reschedule(ArgumentMatchers.<String>any());
verify(producerManager, times(0)).unschedule(ArgumentMatchers.<String>any());
}
@Test
public void assertChildEventWhenStateIsAddAndIsConfigPath() throws Exception {
cloudJobConfigurationListener.childEvent(null, new TreeCacheEvent(TreeCacheEvent.Type.NODE_ADDED, new ChildData("/config/job/test_job", null, CloudJsonConstants.getJobJson().getBytes())));
verify(producerManager).schedule(ArgumentMatchers.<CloudJobConfiguration>any());
}
@Test
public void assertChildEventWhenStateIsUpdateAndIsConfigPathAndTransientJob() throws Exception {
cloudJobConfigurationListener.childEvent(null, new TreeCacheEvent(TreeCacheEvent.Type.NODE_UPDATED, new ChildData("/config/job/test_job", null, CloudJsonConstants.getJobJson().getBytes())));
verify(readyService, times(0)).remove(Collections.singletonList("test_job"));
verify(producerManager).reschedule(ArgumentMatchers.<String>any());
}
@Test
public void assertChildEventWhenStateIsUpdateAndIsConfigPathAndDaemonJob() throws Exception {
cloudJobConfigurationListener.childEvent(null, new TreeCacheEvent(TreeCacheEvent.Type.NODE_UPDATED,
new ChildData("/config/job/test_job", null, CloudJsonConstants.getJobJson(CloudJobExecutionType.DAEMON).getBytes())));
verify(readyService).remove(Collections.singletonList("test_job"));
verify(producerManager).reschedule(ArgumentMatchers.<String>any());
}
@Test
public void assertChildEventWhenStateIsUpdateAndIsConfigPathAndMisfireDisabled() throws Exception {
cloudJobConfigurationListener.childEvent(null, new TreeCacheEvent(TreeCacheEvent.Type.NODE_UPDATED,
new ChildData("/config/job/test_job", null, CloudJsonConstants.getJobJson(false).getBytes())));
verify(readyService).setMisfireDisabled("test_job");
verify(producerManager).reschedule(ArgumentMatchers.<String>any());
}
@Test
public void assertChildEventWhenStateIsRemovedAndIsJobConfigPath() throws Exception {
cloudJobConfigurationListener.childEvent(null, new TreeCacheEvent(TreeCacheEvent.Type.NODE_REMOVED, new ChildData("/config/job/test_job", null, "".getBytes())));
verify(producerManager).unschedule("test_job");
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.config.job;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.producer.ProducerManager;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.state.ready.ReadyService;
import org.apache.shardingsphere.elasticjob.cloud.reg.base.CoordinatorRegistryCenter;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.TreeCache;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent.Type;
import org.apache.curator.framework.recipes.cache.TreeCacheListener;
import java.util.Collections;
import java.util.concurrent.Executors;
/**
* Cloud job configuration change listener.
*/
@Slf4j
public final class CloudJobConfigurationListener implements TreeCacheListener {
private final CoordinatorRegistryCenter regCenter;
private final ProducerManager producerManager;
private final ReadyService readyService;
public CloudJobConfigurationListener(final CoordinatorRegistryCenter regCenter, final ProducerManager producerManager) {
this.regCenter = regCenter;
readyService = new ReadyService(regCenter);
this.producerManager = producerManager;
}
@Override
public void childEvent(final CuratorFramework client, final TreeCacheEvent event) throws Exception {
String path = null == event.getData() ? "" : event.getData().getPath();
if (isJobConfigNode(event, path, Type.NODE_ADDED)) {
CloudJobConfiguration jobConfig = getJobConfig(event);
if (null != jobConfig) {
producerManager.schedule(jobConfig);
}
} else if (isJobConfigNode(event, path, Type.NODE_UPDATED)) {
CloudJobConfiguration jobConfig = getJobConfig(event);
if (null == jobConfig) {
return;
}
if (CloudJobExecutionType.DAEMON == jobConfig.getJobExecutionType()) {
readyService.remove(Collections.singletonList(jobConfig.getJobName()));
}
if (!jobConfig.getTypeConfig().getCoreConfig().isMisfire()) {
readyService.setMisfireDisabled(jobConfig.getJobName());
}
producerManager.reschedule(jobConfig.getJobName());
} else if (isJobConfigNode(event, path, Type.NODE_REMOVED)) {
String jobName = path.substring(CloudJobConfigurationNode.ROOT.length() + 1, path.length());
producerManager.unschedule(jobName);
}
}
private boolean isJobConfigNode(final TreeCacheEvent event, final String path, final Type type) {
return type == event.getType() && path.startsWith(CloudJobConfigurationNode.ROOT) && path.length() > CloudJobConfigurationNode.ROOT.length();
}
private CloudJobConfiguration getJobConfig(final TreeCacheEvent event) {
try {
return CloudJobConfigurationGsonFactory.fromJson(new String(event.getData().getData()));
// CHECKSTYLE:OFF
} catch (final Exception ex) {
log.warn("Wrong Cloud Job Configuration with:", ex.getMessage());
// CHECKSTYLE:ON
return null;
}
}
/**
* Start the listener service of the cloud job service.
*/
public void start() {
getCache().getListenable().addListener(this, Executors.newSingleThreadExecutor());
}
/**
* Stop the listener service of the cloud job service.
*/
public void stop() {
getCache().getListenable().removeListener(this);
}
private TreeCache getCache() {
TreeCache result = (TreeCache) regCenter.getRawCache(CloudJobConfigurationNode.ROOT);
if (null != result) {
return result;
}
regCenter.addCacheData(CloudJobConfigurationNode.ROOT);
return (TreeCache) regCenter.getRawCache(CloudJobConfigurationNode.ROOT);
}
}
```
|
```package org.apache.shardingsphere.elasticjob.cloud.context;
import com.google.common.collect.Lists;
import org.apache.shardingsphere.elasticjob.cloud.fixture.context.TaskNode;
import org.hamcrest.core.Is;
import org.hamcrest.core.StringStartsWith;
import org.junit.Assert;
import org.junit.Test;
public final class TaskContextTest {
@Test
public void assertNew() {
TaskContext actual = new TaskContext("test_job", Lists.newArrayList(0), ExecutionType.READY, "slave-S0");
Assert.assertThat(actual.getMetaInfo().getJobName(), Is.is("test_job"));
Assert.assertThat(actual.getMetaInfo().getShardingItems().get(0), Is.is(0));
Assert.assertThat(actual.getType(), Is.is(ExecutionType.READY));
Assert.assertThat(actual.getSlaveId(), Is.is("slave-S0"));
Assert.assertThat(actual.getId(), StringStartsWith.startsWith(TaskNode.builder().build().getTaskNodeValue().substring(0, TaskNode.builder().build().getTaskNodeValue().length() - 1)));
}
@Test
public void assertNewWithoutSlaveId() {
TaskContext actual = new TaskContext("test_job", Lists.newArrayList(0), ExecutionType.READY);
Assert.assertThat(actual.getSlaveId(), Is.is("unassigned-slave"));
}
@Test
public void assertGetMetaInfo() {
TaskContext actual = new TaskContext("test_job", Lists.newArrayList(0), ExecutionType.READY, "slave-S0");
Assert.assertThat(actual.getMetaInfo().toString(), Is.is("test_job@-@0"));
}
@Test
public void assertTaskContextFrom() {
TaskContext actual = TaskContext.from(TaskNode.builder().build().getTaskNodeValue());
Assert.assertThat(actual.getId(), Is.is(TaskNode.builder().build().getTaskNodeValue()));
Assert.assertThat(actual.getMetaInfo().getJobName(), Is.is("test_job"));
Assert.assertThat(actual.getMetaInfo().getShardingItems().get(0), Is.is(0));
Assert.assertThat(actual.getType(), Is.is(ExecutionType.READY));
Assert.assertThat(actual.getSlaveId(), Is.is("slave-S0"));
}
@Test
public void assertMetaInfoFromWithMetaInfo() {
TaskContext.MetaInfo actual = TaskContext.MetaInfo.from("test_job@-@1");
Assert.assertThat(actual.getJobName(), Is.is("test_job"));
Assert.assertThat(actual.getShardingItems().get(0), Is.is(1));
}
@Test
public void assertMetaInfoFromWithTaskId() {
TaskContext.MetaInfo actual = TaskContext.MetaInfo.from("test_job@-@1@-@READY@-@unassigned-slave@-@0");
Assert.assertThat(actual.getJobName(), Is.is("test_job"));
Assert.assertThat(actual.getShardingItems().get(0), Is.is(1));
}
@Test
public void assertMetaInfoFromWithMetaInfoWithoutShardingItems() {
TaskContext.MetaInfo actual = TaskContext.MetaInfo.from("test_job@-@");
Assert.assertThat(actual.getJobName(), Is.is("test_job"));
Assert.assertTrue(actual.getShardingItems().isEmpty());
}
@Test
public void assertMetaInfoFromWithTaskIdWithoutShardingItems() {
TaskContext.MetaInfo actual = TaskContext.MetaInfo.from("test_job@-@@-@READY@-@unassigned-slave@-@0");
Assert.assertThat(actual.getJobName(), Is.is("test_job"));
Assert.assertTrue(actual.getShardingItems().isEmpty());
}
@Test
public void assertGetIdForUnassignedSlave() {
Assert.assertThat(TaskContext.getIdForUnassignedSlave("test_job@-@0@-@READY@-@slave-S0@-@0"), Is.is("test_job@-@0@-@READY@-@unassigned-slave@-@0"));
}
@Test
public void assertGetTaskName() {
TaskContext actual = TaskContext.from(TaskNode.builder().build().getTaskNodeValue());
Assert.assertThat(actual.getTaskName(), Is.is("test_job@-@0@-@READY@-@slave-S0"));
}
@Test
public void assertGetExecutorId() {
TaskContext actual = TaskContext.from(TaskNode.builder().build().getTaskNodeValue());
Assert.assertThat(actual.getExecutorId("app"), Is.is("app@-@slave-S0"));
}
@Test
public void assertSetSlaveId() {
TaskContext actual = new TaskContext("test_job", Lists.newArrayList(0), ExecutionType.READY, "slave-S0");
Assert.assertThat(actual.getSlaveId(), Is.is("slave-S0"));
actual.setSlaveId("slave-S1");
Assert.assertThat(actual.getSlaveId(), Is.is("slave-S1"));
}
@Test
public void assertSetIdle() {
TaskContext actual = new TaskContext("test_job", Lists.newArrayList(0), ExecutionType.READY, "slave-S0");
Assert.assertFalse(actual.isIdle());
actual.setIdle(true);
Assert.assertTrue(actual.isIdle());
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.shardingsphere.elasticjob.cloud.context;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
/**
* Task runtime context.
*/
@Getter
@EqualsAndHashCode(of = "id")
@ToString(of = "id")
public final class TaskContext {
private static final String DELIMITER = "@-@";
private static final String UNASSIGNED_SLAVE_ID = "unassigned-slave";
private String id;
private final MetaInfo metaInfo;
private final ExecutionType type;
private String slaveId;
@Setter
private boolean idle;
public TaskContext(final String jobName, final List<Integer> shardingItem, final ExecutionType type) {
this(jobName, shardingItem, type, UNASSIGNED_SLAVE_ID);
}
public TaskContext(final String jobName, final List<Integer> shardingItem, final ExecutionType type, final String slaveId) {
metaInfo = new MetaInfo(jobName, shardingItem);
this.type = type;
this.slaveId = slaveId;
id = Joiner.on(DELIMITER).join(metaInfo, type, slaveId, UUID.randomUUID().toString());
}
private TaskContext(final String id, final MetaInfo metaInfo, final ExecutionType type, final String slaveId) {
this.id = id;
this.metaInfo = metaInfo;
this.type = type;
this.slaveId = slaveId;
}
/**
* Get task context via task ID.
*
* @param id task ID
* @return task context
*/
public static TaskContext from(final String id) {
String[] result = id.split(DELIMITER);
Preconditions.checkState(5 == result.length);
return new TaskContext(id, MetaInfo.from(result[0] + DELIMITER + result[1]), ExecutionType.valueOf(result[2]), result[3]);
}
/**
* Get unassigned task ID before job execute.
*
* @param id task ID
* @return unassigned task ID before job execute
*/
public static String getIdForUnassignedSlave(final String id) {
return id.replaceAll(TaskContext.from(id).getSlaveId(), UNASSIGNED_SLAVE_ID);
}
/**
* Set job server ID.
*
* @param slaveId job server ID
*/
public void setSlaveId(final String slaveId) {
id = id.replaceAll(this.slaveId, slaveId);
this.slaveId = slaveId;
}
/**
* Get task name.
*
* @return task name
*/
public String getTaskName() {
return Joiner.on(DELIMITER).join(metaInfo, type, slaveId);
}
/**
* Get executor ID.
*
* @param appName application name
* @return executor ID
*/
public String getExecutorId(final String appName) {
return Joiner.on(DELIMITER).join(appName, slaveId);
}
/**
* Task meta data.
*/
@RequiredArgsConstructor
@Getter
@EqualsAndHashCode
public static class MetaInfo {
private final String jobName;
private final List<Integer> shardingItems;
/**
* Get task meta data info via string.
*
* @param value task meta data info string
* @return task meta data info
*/
public static MetaInfo from(final String value) {
String[] result = value.split(DELIMITER);
Preconditions.checkState(1 == result.length || 2 == result.length || 5 == result.length);
return new MetaInfo(result[0], 1 == result.length || "".equals(result[1]) ? Collections.<Integer>emptyList() : Lists.transform(Splitter.on(",").splitToList(result[1]),
new Function<String, Integer>() {
@Override
public Integer apply(final String input) {
return Integer.parseInt(input);
}
}));
}
@Override
public String toString() {
return Joiner.on(DELIMITER).join(jobName, Joiner.on(",").join(shardingItems));
}
}
}
```
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.mesos;
import org.apache.shardingsphere.elasticjob.cloud.context.TaskContext;
import com.google.common.collect.Sets;
import org.apache.mesos.Protos;
import org.apache.mesos.SchedulerDriver;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public final class ReconcileServiceTest {
@Mock
private SchedulerDriver schedulerDriver;
@Mock
private FacadeService facadeService;
private ReconcileService reconcileService;
@Captor
private ArgumentCaptor<Collection<Protos.TaskStatus>> taskStatusCaptor;
@Before
public void setUp() {
reconcileService = new ReconcileService(schedulerDriver, facadeService);
}
@Test
public void assertRunOneIteration() throws Exception {
reconcileService.runOneIteration();
verify(schedulerDriver).reconcileTasks(Collections.<Protos.TaskStatus>emptyList());
}
@Test
public void assertImplicitReconcile() {
reconcileService.implicitReconcile();
verify(schedulerDriver).reconcileTasks(Collections.<Protos.TaskStatus>emptyList());
}
@Test
public void assertExplicitReconcile() {
Map<String, Set<TaskContext>> runningTaskMap = new HashMap<>();
runningTaskMap.put("transient_test_job", Sets.newHashSet(
TaskContext.from("transient_test_job@-@0@-@READY@-@SLAVE-S0@-@UUID"), TaskContext.from("transient_test_job@-@1@-@READY@-@SLAVE-S0@-@UUID")));
when(facadeService.getAllRunningTasks()).thenReturn(runningTaskMap);
reconcileService.explicitReconcile();
verify(schedulerDriver).reconcileTasks(taskStatusCaptor.capture());
assertThat(taskStatusCaptor.getValue().size(), is(2));
for (Protos.TaskStatus each : taskStatusCaptor.getValue()) {
assertThat(each.getSlaveId().getValue(), is("SLAVE-S0"));
assertThat(each.getState(), is(Protos.TaskState.TASK_RUNNING));
}
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.mesos;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.env.BootstrapEnvironment;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.env.FrameworkConfiguration;
import org.apache.shardingsphere.elasticjob.cloud.context.TaskContext;
import com.google.common.base.Function;
import com.google.common.collect.Collections2;
import com.google.common.util.concurrent.AbstractScheduledService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.mesos.Protos;
import org.apache.mesos.SchedulerDriver;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
/**
* Reconcile service.
*/
@RequiredArgsConstructor
@Slf4j
public class ReconcileService extends AbstractScheduledService {
private final SchedulerDriver schedulerDriver;
private final FacadeService facadeService;
private final ReentrantLock lock = new ReentrantLock();
@Override
protected void runOneIteration() throws Exception {
lock.lock();
try {
explicitReconcile();
implicitReconcile();
} finally {
lock.unlock();
}
}
/**
* Explicit reconcile service.
*/
public void explicitReconcile() {
lock.lock();
try {
Set<TaskContext> runningTask = new HashSet<>();
for (Set<TaskContext> each : facadeService.getAllRunningTasks().values()) {
runningTask.addAll(each);
}
if (runningTask.isEmpty()) {
return;
}
log.info("Requesting {} tasks reconciliation with the Mesos master", runningTask.size());
schedulerDriver.reconcileTasks(Collections2.transform(runningTask, new Function<TaskContext, Protos.TaskStatus>() {
@Override
public Protos.TaskStatus apply(final TaskContext input) {
return Protos.TaskStatus.newBuilder()
.setTaskId(Protos.TaskID.newBuilder().setValue(input.getId()).build())
.setSlaveId(Protos.SlaveID.newBuilder().setValue(input.getSlaveId()).build())
.setState(Protos.TaskState.TASK_RUNNING).build();
}
}));
} finally {
lock.unlock();
}
}
/**
* Implicit reconcile service.
*/
public void implicitReconcile() {
lock.lock();
try {
schedulerDriver.reconcileTasks(Collections.<Protos.TaskStatus>emptyList());
} finally {
lock.unlock();
}
}
@Override
protected Scheduler scheduler() {
FrameworkConfiguration configuration = BootstrapEnvironment.getInstance().getFrameworkConfiguration();
return Scheduler.newFixedDelaySchedule(configuration.getReconcileIntervalMinutes(), configuration.getReconcileIntervalMinutes(), TimeUnit.MINUTES);
}
}
```
|
```package org.apache.shardingsphere.elasticjob.cloud.util.env;
import org.junit.Assert;
import org.junit.Test;
public class TimeServiceTest {
private TimeService timeService = new TimeService();
@Test
public void assertGetCurrentMillis() throws Exception {
Assert.assertTrue(timeService.getCurrentMillis() <= System.currentTimeMillis());
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.shardingsphere.elasticjob.cloud.util.env;
/**
* Time service.
*/
public final class TimeService {
/**
* Get current millis.
*
* @return current millis
*/
public long getCurrentMillis() {
return System.currentTimeMillis();
}
}
```
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.mesos;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.ha.HANode;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.restful.AbstractCloudRestfulApiTest;
import org.apache.shardingsphere.elasticjob.cloud.reg.base.CoordinatorRegistryCenter;
import com.google.gson.JsonArray;
import org.hamcrest.core.Is;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.Collection;
@RunWith(MockitoJUnitRunner.class)
public class MesosStateServiceTest extends AbstractCloudRestfulApiTest {
@Mock
private CoordinatorRegistryCenter registryCenter;
@Test
public void assertSandbox() throws Exception {
Mockito.when(registryCenter.getDirectly(HANode.FRAMEWORK_ID_NODE)).thenReturn("d8701508-41b7-471e-9b32-61cf824a660d-0000");
MesosStateService service = new MesosStateService(registryCenter);
JsonArray sandbox = service.sandbox("foo_app");
Assert.assertThat(sandbox.size(), Is.is(1));
Assert.assertThat(sandbox.get(0).getAsJsonObject().get("hostname").getAsString(), Is.is("127.0.0.1"));
Assert.assertThat(sandbox.get(0).getAsJsonObject().get("path").getAsString(), Is.is("/slaves/d8701508-41b7-471e-9b32-61cf824a660d-S0/"
+ "frameworks/d8701508-41b7-471e-9b32-61cf824a660d-0000/executors/foo_app@-@d8701508-41b7-471e-9b32-61cf824a660d-S0/runs/53fb4af7-aee2-44f6-9e47-6f418d9f27e1"));
}
@Test
public void assertExecutors() throws Exception {
Mockito.when(registryCenter.getDirectly(HANode.FRAMEWORK_ID_NODE)).thenReturn("d8701508-41b7-471e-9b32-61cf824a660d-0000");
MesosStateService service = new MesosStateService(registryCenter);
Collection<MesosStateService.ExecutorStateInfo> executorStateInfo = service.executors("foo_app");
Assert.assertThat(executorStateInfo.size(), Is.is(1));
MesosStateService.ExecutorStateInfo executor = executorStateInfo.iterator().next();
Assert.assertThat(executor.getId(), Is.is("foo_app@-@d8701508-41b7-471e-9b32-61cf824a660d-S0"));
Assert.assertThat(executor.getSlaveId(), Is.is("d8701508-41b7-471e-9b32-61cf824a660d-S0"));
}
@Test
public void assertAllExecutors() throws Exception {
Mockito.when(registryCenter.getDirectly(HANode.FRAMEWORK_ID_NODE)).thenReturn("d8701508-41b7-471e-9b32-61cf824a660d-0000");
MesosStateService service = new MesosStateService(registryCenter);
Collection<MesosStateService.ExecutorStateInfo> executorStateInfo = service.executors();
Assert.assertThat(executorStateInfo.size(), Is.is(1));
MesosStateService.ExecutorStateInfo executor = executorStateInfo.iterator().next();
Assert.assertThat(executor.getId(), Is.is("foo_app@-@d8701508-41b7-471e-9b32-61cf824a660d-S0"));
Assert.assertThat(executor.getSlaveId(), Is.is("d8701508-41b7-471e-9b32-61cf824a660d-S0"));
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.mesos;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.ha.FrameworkIDService;
import org.apache.shardingsphere.elasticjob.cloud.reg.base.CoordinatorRegistryCenter;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.Collections2;
import com.google.common.collect.Lists;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.sun.jersey.api.client.Client;
import lombok.Builder;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import java.util.Collection;
import java.util.List;
/**
* Mesos state service.
*/
@Slf4j
public class MesosStateService {
private static String stateUrl;
private final FrameworkIDService frameworkIDService;
public MesosStateService(final CoordinatorRegistryCenter regCenter) {
frameworkIDService = new FrameworkIDService(regCenter);
}
/**
* Register master info of Mesos.
*
* @param hostName hostname of master
* @param port port of master
*/
public static synchronized void register(final String hostName, final int port) {
stateUrl = String.format("http://%s:%d/state", hostName, port);
}
/**
* Deregister master info of Mesos.
*/
public static synchronized void deregister() {
stateUrl = null;
}
/**
* Get sandbox info.
*
* @param appName app name
* @return sandbox info in json format
* @throws JSONException parse json exception
*/
public JsonArray sandbox(final String appName) throws JSONException {
JSONObject state = fetch(stateUrl);
JsonArray result = new JsonArray();
for (JSONObject each : findExecutors(state.getJSONArray("frameworks"), appName)) {
JSONArray slaves = state.getJSONArray("slaves");
String slaveHost = null;
for (int i = 0; i < slaves.length(); i++) {
JSONObject slave = slaves.getJSONObject(i);
if (each.getString("slave_id").equals(slave.getString("id"))) {
slaveHost = slave.getString("pid").split("@")[1];
}
}
Preconditions.checkNotNull(slaveHost);
JSONObject slaveState = fetch(String.format("http://%s/state", slaveHost));
String workDir = slaveState.getJSONObject("flags").getString("work_dir");
Collection<JSONObject> executorsOnSlave = findExecutors(slaveState.getJSONArray("frameworks"), appName);
for (JSONObject executorOnSlave : executorsOnSlave) {
JsonObject r = new JsonObject();
r.addProperty("hostname", slaveState.getString("hostname"));
r.addProperty("path", executorOnSlave.getString("directory").replace(workDir, ""));
result.add(r);
}
}
return result;
}
/**
* Get executor by app name.
*
* @param appName app name
* @return executor state info
* @throws JSONException parse json exception
*/
public Collection<ExecutorStateInfo> executors(final String appName) throws JSONException {
return Collections2.transform(findExecutors(fetch(stateUrl).getJSONArray("frameworks"), appName), new Function<JSONObject, ExecutorStateInfo>() {
@Override
public ExecutorStateInfo apply(final JSONObject input) {
try {
return ExecutorStateInfo.builder().id(getExecutorId(input)).slaveId(input.getString("slave_id")).build();
} catch (final JSONException ex) {
throw new RuntimeException(ex);
}
}
});
}
/**
* Get all executors.
*
* @return collection of executor state info
* @throws JSONException parse json exception
*/
public Collection<ExecutorStateInfo> executors() throws JSONException {
return executors(null);
}
private JSONObject fetch(final String url) {
Preconditions.checkState(!Strings.isNullOrEmpty(url));
return Client.create().resource(url).get(JSONObject.class);
}
private Collection<JSONObject> findExecutors(final JSONArray frameworks, final String appName) throws JSONException {
List<JSONObject> result = Lists.newArrayList();
Optional<String> frameworkIDOptional = frameworkIDService.fetch();
String frameworkID;
if (frameworkIDOptional.isPresent()) {
frameworkID = frameworkIDOptional.get();
} else {
return result;
}
for (int i = 0; i < frameworks.length(); i++) {
JSONObject framework = frameworks.getJSONObject(i);
if (!framework.getString("id").equals(frameworkID)) {
continue;
}
JSONArray executors = framework.getJSONArray("executors");
for (int j = 0; j < executors.length(); j++) {
JSONObject executor = executors.getJSONObject(j);
if (null == appName || appName.equals(getExecutorId(executor).split("@-@")[0])) {
result.add(executor);
}
}
}
return result;
}
private String getExecutorId(final JSONObject executor) throws JSONException {
return executor.has("id") ? executor.getString("id") : executor.getString("executor_id");
}
@Builder
@Getter
public static final class ExecutorStateInfo {
private final String id;
private final String slaveId;
}
}
```
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.state.running;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.fixture.TaskNode;
import org.hamcrest.core.Is;
import org.junit.Assert;
import org.junit.Test;
public final class RunningNodeTest {
@Test
public void assertGetRunningJobNodePath() {
Assert.assertThat(RunningNode.getRunningJobNodePath("test_job"), Is.is("/state/running/test_job"));
}
@Test
public void assertGetRunningTaskNodePath() {
String nodePath = TaskNode.builder().build().getTaskNodePath();
Assert.assertThat(RunningNode.getRunningTaskNodePath(nodePath), Is.is("/state/running/test_job/" + nodePath));
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.state.running;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.state.StateNode;
import org.apache.shardingsphere.elasticjob.cloud.context.TaskContext;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
/**
* Running node.
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
final class RunningNode {
static final String ROOT = StateNode.ROOT + "/running";
private static final String RUNNING_JOB = ROOT + "/%s";
private static final String RUNNING_TASK = RUNNING_JOB + "/%s";
static String getRunningJobNodePath(final String jobName) {
return String.format(RUNNING_JOB, jobName);
}
static String getRunningTaskNodePath(final String taskMetaInfo) {
return String.format(RUNNING_TASK, TaskContext.MetaInfo.from(taskMetaInfo).getJobName(), taskMetaInfo);
}
}
```
|
```package org.apache.shardingsphere.elasticjob.cloud.event.fixture;
import org.apache.shardingsphere.elasticjob.cloud.event.JobEventConfiguration;
import org.apache.shardingsphere.elasticjob.cloud.event.JobEventListener;
import org.apache.shardingsphere.elasticjob.cloud.event.JobEventListenerConfigurationException;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
public final class TestJobEventConfiguration extends TestJobEventIdentity implements JobEventConfiguration {
private final JobEventCaller jobEventCaller;
@Override
public JobEventListener createJobEventListener() throws JobEventListenerConfigurationException {
return new TestJobEventListener(jobEventCaller);
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.shardingsphere.elasticjob.cloud.event;
/**
* Job event configuration.
*/
public interface JobEventConfiguration extends JobEventIdentity {
/**
* Create job event listener.
*
* @return Job event listener
* @throws JobEventListenerConfigurationException job event listener configuration exception
*/
JobEventListener createJobEventListener() throws JobEventListenerConfigurationException;
}
```
|
```package org.apache.shardingsphere.elasticjob.cloud.exception;
import org.hamcrest.core.Is;
import org.junit.Assert;
import org.junit.Test;
public final class ExceptionUtilTest {
@Test
public void assertTransformWithError() {
Assert.assertTrue(ExceptionUtil.transform(new Error("Error")).startsWith("java.lang.Error"));
}
@Test
public void assertTransformWithException() {
Assert.assertTrue(ExceptionUtil.transform(new Exception("Exception")).startsWith("java.lang.Exception"));
}
@Test
public void assertTransformWithNull() {
Assert.assertThat(ExceptionUtil.transform(null), Is.is(""));
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.shardingsphere.elasticjob.cloud.exception;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import java.io.PrintWriter;
import java.io.StringWriter;
/**
* Exception utility.
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class ExceptionUtil {
/**
* Transform throwable to string.
*
* @param cause cause
* @return string
*/
public static String transform(final Throwable cause) {
if (null == cause) {
return "";
}
StringWriter result = new StringWriter();
try (PrintWriter writer = new PrintWriter(result)) {
cause.printStackTrace(writer);
}
return result.toString();
}
}
```
|
```package org.apache.shardingsphere.elasticjob.cloud.config;
import org.apache.shardingsphere.elasticjob.cloud.executor.handler.impl.DefaultJobExceptionHandler;
import org.apache.shardingsphere.elasticjob.cloud.fixture.handler.IgnoreJobExceptionHandler;
import org.apache.shardingsphere.elasticjob.cloud.executor.handler.JobProperties;
import org.hamcrest.core.Is;
import org.junit.Assert;
import org.junit.Test;
public final class JobCoreConfigurationTest {
@Test
public void assertBuildAllProperties() {
JobCoreConfiguration actual = JobCoreConfiguration.newBuilder("test_job", "0/1 * * * * ?", 3)
.shardingItemParameters("0=a,1=b,2=c").jobParameter("param").failover(true).misfire(false).description("desc")
.jobProperties("job_exception_handler", IgnoreJobExceptionHandler.class.getName()).build();
assertRequiredProperties(actual);
Assert.assertThat(actual.getShardingItemParameters(), Is.is("0=a,1=b,2=c"));
Assert.assertThat(actual.getJobParameter(), Is.is("param"));
Assert.assertTrue(actual.isFailover());
Assert.assertFalse(actual.isMisfire());
Assert.assertThat(actual.getDescription(), Is.is("desc"));
Assert.assertThat(actual.getJobProperties().get(JobProperties.JobPropertiesEnum.JOB_EXCEPTION_HANDLER), Is.is(IgnoreJobExceptionHandler.class.getName()));
}
@Test
public void assertBuildRequiredProperties() {
JobCoreConfiguration actual = JobCoreConfiguration.newBuilder("test_job", "0/1 * * * * ?", 3).build();
assertRequiredProperties(actual);
assertDefaultValues(actual);
}
@Test
public void assertBuildWhenOptionalParametersIsNull() {
//noinspection NullArgumentToVariableArgMethod
JobCoreConfiguration actual = JobCoreConfiguration.newBuilder("test_job", "0/1 * * * * ?", 3).shardingItemParameters(null).jobParameter(null).description(null).build();
assertRequiredProperties(actual);
assertDefaultValues(actual);
}
private void assertRequiredProperties(final JobCoreConfiguration actual) {
Assert.assertThat(actual.getJobName(), Is.is("test_job"));
Assert.assertThat(actual.getCron(), Is.is("0/1 * * * * ?"));
Assert.assertThat(actual.getShardingTotalCount(), Is.is(3));
}
private void assertDefaultValues(final JobCoreConfiguration actual) {
Assert.assertThat(actual.getShardingItemParameters(), Is.is(""));
Assert.assertThat(actual.getJobParameter(), Is.is(""));
Assert.assertFalse(actual.isFailover());
Assert.assertTrue(actual.isMisfire());
Assert.assertThat(actual.getDescription(), Is.is(""));
Assert.assertThat(actual.getJobProperties().get(JobProperties.JobPropertiesEnum.JOB_EXCEPTION_HANDLER), Is.is(DefaultJobExceptionHandler.class.getName()));
}
@Test(expected = IllegalArgumentException.class)
public void assertBuildWhenJobNameIsNull() {
JobCoreConfiguration.newBuilder(null, "0/1 * * * * ?", 3).build();
}
@Test(expected = IllegalArgumentException.class)
public void assertBuildWhenCronIsNull() {
JobCoreConfiguration.newBuilder("test_job", null, 3).build();
}
@Test(expected = IllegalArgumentException.class)
public void assertBuildWhenTotalSHardingCountIsNegative() {
JobCoreConfiguration.newBuilder(null, "0/1 * * * * ?", -1).build();
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.shardingsphere.elasticjob.cloud.config;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import org.apache.shardingsphere.elasticjob.cloud.executor.handler.JobProperties;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
/**
* Job core configuration.
*/
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@Getter
public final class JobCoreConfiguration {
private final String jobName;
private final String cron;
private final int shardingTotalCount;
private final String shardingItemParameters;
private final String jobParameter;
private final boolean failover;
private final boolean misfire;
private final String description;
private final JobProperties jobProperties;
/**
* Create simple job configuration builder.
*
* @param jobName job name
* @param cron cron expression for job trigger
* @param shardingTotalCount sharding total count
* @return simple job configuration builder
*/
public static Builder newBuilder(final String jobName, final String cron, final int shardingTotalCount) {
return new Builder(jobName, cron, shardingTotalCount);
}
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
public static class Builder {
private final String jobName;
private final String cron;
private final int shardingTotalCount;
private String shardingItemParameters = "";
private String jobParameter = "";
private boolean failover;
private boolean misfire = true;
private String description = "";
private final JobProperties jobProperties = new JobProperties();
/**
* Set mapper of sharding items and sharding parameters.
*
* <p>
* sharding item and sharding parameter split by =, multiple sharding items and sharding parameters split by comma, just like map.
* Sharding item start from zero, cannot equal to great than sharding total count.
*
* For example:
* 0=a,1=b,2=c
* </p>
*
* @param shardingItemParameters mapper of sharding items and sharding parameters
*
* @return job configuration builder
*/
public Builder shardingItemParameters(final String shardingItemParameters) {
if (null != shardingItemParameters) {
this.shardingItemParameters = shardingItemParameters;
}
return this;
}
/**
* Set job parameter.
*
* @param jobParameter job parameter
*
* @return job configuration builder
*/
public Builder jobParameter(final String jobParameter) {
if (null != jobParameter) {
this.jobParameter = jobParameter;
}
return this;
}
/**
* Set enable failover.
*
* <p>
* Only for `monitorExecution` enabled.
* </p>
*
* @param failover enable or disable failover
*
* @return job configuration builder
*/
public Builder failover(final boolean failover) {
this.failover = failover;
return this;
}
/**
* Set enable misfire.
*
* @param misfire enable or disable misfire
*
* @return job configuration builder
*/
public Builder misfire(final boolean misfire) {
this.misfire = misfire;
return this;
}
/**
* Set job description.
*
* @param description job description
*
* @return job configuration builder
*/
public Builder description(final String description) {
if (null != description) {
this.description = description;
}
return this;
}
/**
* Set job properties.
*
* @param key property key
* @param value property value
*
* @return job configuration builder
*/
public Builder jobProperties(final String key, final String value) {
jobProperties.put(key, value);
return this;
}
/**
* Build Job.
*
* @return job configuration builder
*/
public final JobCoreConfiguration build() {
Preconditions.checkArgument(!Strings.isNullOrEmpty(jobName), "jobName can not be empty.");
Preconditions.checkArgument(!Strings.isNullOrEmpty(cron), "cron can not be empty.");
Preconditions.checkArgument(shardingTotalCount > 0, "shardingTotalCount should larger than zero.");
return new JobCoreConfiguration(jobName, cron, shardingTotalCount, shardingItemParameters, jobParameter, failover, misfire, description, jobProperties);
}
}
}
```
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.state.failover;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.fixture.CloudJobConfigurationBuilder;
import org.apache.shardingsphere.elasticjob.cloud.context.ExecutionType;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.config.job.CloudJobConfiguration;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.config.job.CloudJobConfigurationService;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.context.JobContext;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.env.BootstrapEnvironment;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.fixture.TaskNode;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.state.running.RunningService;
import org.apache.shardingsphere.elasticjob.cloud.context.TaskContext;
import org.apache.shardingsphere.elasticjob.cloud.reg.base.CoordinatorRegistryCenter;
import com.google.common.base.Optional;
import com.google.common.collect.Lists;
import org.hamcrest.core.Is;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.unitils.util.ReflectionUtils;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.UUID;
@RunWith(MockitoJUnitRunner.class)
public final class FailoverServiceTest {
@Mock
private CoordinatorRegistryCenter regCenter;
@Mock
private CloudJobConfigurationService configService;
@Mock
private RunningService runningService;
@Mock
private List<String> mockedFailoverQueue;
private FailoverService failoverService;
@Before
public void setUp() throws NoSuchFieldException {
failoverService = new FailoverService(regCenter);
ReflectionUtils.setFieldValue(failoverService, "configService", configService);
ReflectionUtils.setFieldValue(failoverService, "runningService", runningService);
}
@Test
public void assertAddWhenJobIsOverQueueSize() {
Mockito.when(regCenter.getNumChildren(FailoverNode.ROOT)).thenReturn(BootstrapEnvironment.getInstance().getFrameworkConfiguration().getJobStateQueueSize() + 1);
TaskNode taskNode = TaskNode.builder().type(ExecutionType.FAILOVER).build();
failoverService.add(TaskContext.from(taskNode.getTaskNodeValue()));
Mockito.verify(regCenter, Mockito.times(0)).persist("/state/failover/test_job/" + taskNode.getTaskNodePath(), taskNode.getTaskNodeValue());
}
@Test
public void assertAddWhenExisted() {
TaskNode taskNode = TaskNode.builder().type(ExecutionType.FAILOVER).build();
Mockito.when(regCenter.isExisted("/state/failover/test_job/" + taskNode.getTaskNodePath())).thenReturn(true);
failoverService.add(TaskContext.from(taskNode.getTaskNodeValue()));
Mockito.verify(regCenter).isExisted("/state/failover/test_job/" + taskNode.getTaskNodePath());
Mockito.verify(regCenter, Mockito.times(0)).persist("/state/failover/test_job/" + taskNode.getTaskNodePath(), taskNode.getTaskNodeValue());
}
@Test
public void assertAddWhenNotExistedAndTaskIsRunning() {
TaskNode taskNode = TaskNode.builder().type(ExecutionType.FAILOVER).build();
Mockito.when(regCenter.isExisted("/state/failover/test_job/" + taskNode.getTaskNodePath())).thenReturn(false);
Mockito.when(runningService.isTaskRunning(TaskContext.MetaInfo.from(taskNode.getTaskNodePath()))).thenReturn(true);
failoverService.add(TaskContext.from(taskNode.getTaskNodeValue()));
Mockito.verify(regCenter).isExisted("/state/failover/test_job/" + taskNode.getTaskNodePath());
Mockito.verify(runningService).isTaskRunning(TaskContext.MetaInfo.from(taskNode.getTaskNodePath()));
Mockito.verify(regCenter, Mockito.times(0)).persist("/state/failover/test_job/" + taskNode.getTaskNodePath(), taskNode.getTaskNodeValue());
}
@Test
public void assertAddWhenNotExistedAndTaskIsNotRunning() {
TaskNode taskNode = TaskNode.builder().type(ExecutionType.FAILOVER).build();
Mockito.when(regCenter.isExisted("/state/failover/test_job/" + taskNode.getTaskNodePath())).thenReturn(false);
Mockito.when(runningService.isTaskRunning(TaskContext.MetaInfo.from(taskNode.getTaskNodePath()))).thenReturn(false);
failoverService.add(TaskContext.from(taskNode.getTaskNodeValue()));
Mockito.verify(regCenter).isExisted("/state/failover/test_job/" + taskNode.getTaskNodePath());
Mockito.verify(runningService).isTaskRunning(TaskContext.MetaInfo.from(taskNode.getTaskNodePath()));
Mockito.verify(regCenter).persist("/state/failover/test_job/" + taskNode.getTaskNodePath(), taskNode.getTaskNodeValue());
}
@Test
public void assertGetAllEligibleJobContextsWithoutRootNode() {
Mockito.when(regCenter.isExisted("/state/failover")).thenReturn(false);
Assert.assertTrue(failoverService.getAllEligibleJobContexts().isEmpty());
Mockito.verify(regCenter).isExisted("/state/failover");
}
@Test
public void assertGetAllEligibleJobContextsWithRootNode() {
Mockito.when(regCenter.isExisted("/state/failover")).thenReturn(true);
Mockito.when(regCenter.getChildrenKeys("/state/failover")).thenReturn(Arrays.asList("task_empty_job", "not_existed_job", "eligible_job"));
Mockito.when(regCenter.getChildrenKeys("/state/failover/task_empty_job")).thenReturn(Collections.<String>emptyList());
Mockito.when(regCenter.getChildrenKeys("/state/failover/not_existed_job")).thenReturn(Arrays.asList(
TaskNode.builder().jobName("not_existed_job").build().getTaskNodePath(), TaskNode.builder().jobName("not_existed_job").shardingItem(1).build().getTaskNodePath()));
String eligibleJobNodePath1 = TaskNode.builder().jobName("eligible_job").build().getTaskNodePath();
String eligibleJobNodePath2 = TaskNode.builder().jobName("eligible_job").shardingItem(1).build().getTaskNodePath();
Mockito.when(regCenter.getChildrenKeys("/state/failover/eligible_job")).thenReturn(Arrays.asList(eligibleJobNodePath1, eligibleJobNodePath2));
Mockito.when(configService.load("not_existed_job")).thenReturn(Optional.<CloudJobConfiguration>absent());
Mockito.when(configService.load("eligible_job")).thenReturn(Optional.of(CloudJobConfigurationBuilder.createCloudJobConfiguration("eligible_job")));
Mockito.when(runningService.isTaskRunning(TaskContext.MetaInfo.from(eligibleJobNodePath1))).thenReturn(true);
Mockito.when(runningService.isTaskRunning(TaskContext.MetaInfo.from(eligibleJobNodePath2))).thenReturn(false);
Collection<JobContext> actual = failoverService.getAllEligibleJobContexts();
Assert.assertThat(actual.size(), Is.is(1));
Assert.assertThat(actual.iterator().next().getAssignedShardingItems().size(), Is.is(1));
Assert.assertThat(actual.iterator().next().getAssignedShardingItems().get(0), Is.is(1));
Mockito.verify(regCenter).isExisted("/state/failover");
Mockito.verify(regCenter).remove("/state/failover/task_empty_job");
Mockito.verify(regCenter).remove("/state/failover/not_existed_job");
}
@Test
public void assertRemove() {
String jobNodePath1 = TaskNode.builder().type(ExecutionType.FAILOVER).build().getTaskNodePath();
String jobNodePath2 = TaskNode.builder().shardingItem(1).type(ExecutionType.FAILOVER).build().getTaskNodePath();
failoverService.remove(Arrays.asList(TaskContext.MetaInfo.from(jobNodePath1), TaskContext.MetaInfo.from(jobNodePath2)));
Mockito.verify(regCenter).remove("/state/failover/test_job/" + jobNodePath1);
Mockito.verify(regCenter).remove("/state/failover/test_job/" + jobNodePath2);
}
@Test
public void assertGetTaskId() {
TaskNode taskNode = TaskNode.builder().type(ExecutionType.FAILOVER).build();
failoverService.add(TaskContext.from(taskNode.getTaskNodeValue()));
Mockito.when(regCenter.isExisted("/state/failover/test_job/" + taskNode.getTaskNodePath())).thenReturn(true);
Mockito.when(regCenter.get("/state/failover/test_job/" + taskNode.getTaskNodePath())).thenReturn(taskNode.getTaskNodeValue());
Assert.assertThat(failoverService.getTaskId(taskNode.getMetaInfo()).get(), Is.is(taskNode.getTaskNodeValue()));
Mockito.verify(regCenter, Mockito.times(2)).isExisted("/state/failover/test_job/" + taskNode.getTaskNodePath());
}
@Test
public void assertGetAllFailoverTasksWithoutRootNode() {
Mockito.when(regCenter.isExisted(FailoverNode.ROOT)).thenReturn(false);
Assert.assertTrue(failoverService.getAllFailoverTasks().isEmpty());
Mockito.verify(regCenter).isExisted(FailoverNode.ROOT);
}
@Test
public void assertGetAllFailoverTasksWhenRootNodeHasNoChild() {
Mockito.when(regCenter.isExisted(FailoverNode.ROOT)).thenReturn(true);
Mockito.when(regCenter.getChildrenKeys(FailoverNode.ROOT)).thenReturn(Collections.<String>emptyList());
Assert.assertTrue(failoverService.getAllFailoverTasks().isEmpty());
Mockito.verify(regCenter).isExisted(FailoverNode.ROOT);
Mockito.verify(regCenter).getChildrenKeys(FailoverNode.ROOT);
}
@Test
public void assertGetAllFailoverTasksWhenJobNodeHasNoChild() {
Mockito.when(regCenter.isExisted(FailoverNode.ROOT)).thenReturn(true);
Mockito.when(regCenter.getChildrenKeys(FailoverNode.ROOT)).thenReturn(Lists.newArrayList("test_job"));
Mockito.when(regCenter.getChildrenKeys(FailoverNode.getFailoverJobNodePath("test_job"))).thenReturn(Collections.<String>emptyList());
Assert.assertTrue(failoverService.getAllFailoverTasks().isEmpty());
Mockito.verify(regCenter).isExisted(FailoverNode.ROOT);
Mockito.verify(regCenter).getChildrenKeys(FailoverNode.ROOT);
Mockito.verify(regCenter).getChildrenKeys(FailoverNode.getFailoverJobNodePath("test_job"));
}
@Test
public void assertGetAllFailoverTasksWithRootNode() {
String uuid1 = UUID.randomUUID().toString();
String uuid2 = UUID.randomUUID().toString();
String uuid3 = UUID.randomUUID().toString();
Mockito.when(regCenter.isExisted(FailoverNode.ROOT)).thenReturn(true);
Mockito.when(regCenter.getChildrenKeys(FailoverNode.ROOT)).thenReturn(Lists.newArrayList("test_job_1", "test_job_2"));
Mockito.when(regCenter.getChildrenKeys(FailoverNode.getFailoverJobNodePath("test_job_1"))).thenReturn(Lists.newArrayList("test_job_1@-@0", "test_job_1@-@1"));
Mockito.when(regCenter.getChildrenKeys(FailoverNode.getFailoverJobNodePath("test_job_2"))).thenReturn(Lists.newArrayList("test_job_2@-@0"));
Mockito.when(regCenter.get(FailoverNode.getFailoverTaskNodePath("test_job_1@-@0"))).thenReturn(uuid1);
Mockito.when(regCenter.get(FailoverNode.getFailoverTaskNodePath("test_job_1@-@1"))).thenReturn(uuid2);
Mockito.when(regCenter.get(FailoverNode.getFailoverTaskNodePath("test_job_2@-@0"))).thenReturn(uuid3);
Map<String, Collection<FailoverTaskInfo>> result = failoverService.getAllFailoverTasks();
Assert.assertThat(result.size(), Is.is(2));
Assert.assertThat(result.get("test_job_1").size(), Is.is(2));
Assert.assertThat(result.get("test_job_1").toArray(new FailoverTaskInfo[]{})[0].getTaskInfo().toString(), Is.is("test_job_1@-@0"));
Assert.assertThat(result.get("test_job_1").toArray(new FailoverTaskInfo[]{})[0].getOriginalTaskId(), Is.is(uuid1));
Assert.assertThat(result.get("test_job_1").toArray(new FailoverTaskInfo[]{})[1].getTaskInfo().toString(), Is.is("test_job_1@-@1"));
Assert.assertThat(result.get("test_job_1").toArray(new FailoverTaskInfo[]{})[1].getOriginalTaskId(), Is.is(uuid2));
Assert.assertThat(result.get("test_job_2").size(), Is.is(1));
Assert.assertThat(result.get("test_job_2").iterator().next().getTaskInfo().toString(), Is.is("test_job_2@-@0"));
Assert.assertThat(result.get("test_job_2").iterator().next().getOriginalTaskId(), Is.is(uuid3));
Mockito.verify(regCenter).isExisted(FailoverNode.ROOT);
Mockito.verify(regCenter).getChildrenKeys(FailoverNode.ROOT);
Mockito.verify(regCenter).getChildrenKeys(FailoverNode.getFailoverJobNodePath("test_job_1"));
Mockito.verify(regCenter).getChildrenKeys(FailoverNode.getFailoverJobNodePath("test_job_2"));
Mockito.verify(regCenter).get(FailoverNode.getFailoverTaskNodePath("test_job_1@-@0"));
Mockito.verify(regCenter).get(FailoverNode.getFailoverTaskNodePath("test_job_1@-@1"));
Mockito.verify(regCenter).get(FailoverNode.getFailoverTaskNodePath("test_job_2@-@0"));
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.state.failover;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.config.job.CloudJobConfiguration;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.config.job.CloudJobConfigurationService;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.env.BootstrapEnvironment;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.state.running.RunningService;
import org.apache.shardingsphere.elasticjob.cloud.context.ExecutionType;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.context.JobContext;
import org.apache.shardingsphere.elasticjob.cloud.context.TaskContext;
import org.apache.shardingsphere.elasticjob.cloud.reg.base.CoordinatorRegistryCenter;
import com.google.common.base.Charsets;
import com.google.common.base.Optional;
import com.google.common.base.Strings;
import com.google.common.hash.HashCode;
import com.google.common.hash.Hashing;
import lombok.extern.slf4j.Slf4j;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Failover service.
*/
@Slf4j
public final class FailoverService {
private final BootstrapEnvironment env = BootstrapEnvironment.getInstance();
private final CoordinatorRegistryCenter regCenter;
private final CloudJobConfigurationService configService;
private final RunningService runningService;
public FailoverService(final CoordinatorRegistryCenter regCenter) {
this.regCenter = regCenter;
configService = new CloudJobConfigurationService(regCenter);
runningService = new RunningService(regCenter);
}
/**
* Add task to failover queue.
*
* @param taskContext task running context
*/
public void add(final TaskContext taskContext) {
if (regCenter.getNumChildren(FailoverNode.ROOT) > env.getFrameworkConfiguration().getJobStateQueueSize()) {
log.warn("Cannot add job, caused by read state queue size is larger than {}.", env.getFrameworkConfiguration().getJobStateQueueSize());
return;
}
String failoverTaskNodePath = FailoverNode.getFailoverTaskNodePath(taskContext.getMetaInfo().toString());
if (!regCenter.isExisted(failoverTaskNodePath) && !runningService.isTaskRunning(taskContext.getMetaInfo())) {
// TODO Whether Daemon-type jobs increase storage and fail immediately?
regCenter.persist(failoverTaskNodePath, taskContext.getId());
}
}
/**
* Get all eligible job contexts from failover queue.
*
* @return collection of the eligible job contexts
*/
public Collection<JobContext> getAllEligibleJobContexts() {
if (!regCenter.isExisted(FailoverNode.ROOT)) {
return Collections.emptyList();
}
List<String> jobNames = regCenter.getChildrenKeys(FailoverNode.ROOT);
Collection<JobContext> result = new ArrayList<>(jobNames.size());
Set<HashCode> assignedTasks = new HashSet<>(jobNames.size() * 10, 1);
for (String each : jobNames) {
List<String> taskIdList = regCenter.getChildrenKeys(FailoverNode.getFailoverJobNodePath(each));
if (taskIdList.isEmpty()) {
regCenter.remove(FailoverNode.getFailoverJobNodePath(each));
continue;
}
Optional<CloudJobConfiguration> jobConfig = configService.load(each);
if (!jobConfig.isPresent()) {
regCenter.remove(FailoverNode.getFailoverJobNodePath(each));
continue;
}
List<Integer> assignedShardingItems = getAssignedShardingItems(each, taskIdList, assignedTasks);
if (!assignedShardingItems.isEmpty() && jobConfig.isPresent()) {
result.add(new JobContext(jobConfig.get(), assignedShardingItems, ExecutionType.FAILOVER));
}
}
return result;
}
private List<Integer> getAssignedShardingItems(final String jobName, final List<String> taskIdList, final Set<HashCode> assignedTasks) {
List<Integer> result = new ArrayList<>(taskIdList.size());
for (String each : taskIdList) {
TaskContext.MetaInfo metaInfo = TaskContext.MetaInfo.from(each);
if (assignedTasks.add(Hashing.md5().newHasher().putString(jobName, Charsets.UTF_8).putInt(metaInfo.getShardingItems().get(0)).hash()) && !runningService.isTaskRunning(metaInfo)) {
result.add(metaInfo.getShardingItems().get(0));
}
}
return result;
}
/**
* Remove task from the failover queue.
*
* @param metaInfoList collection of task meta infos to be removed
*/
public void remove(final Collection<TaskContext.MetaInfo> metaInfoList) {
for (TaskContext.MetaInfo each : metaInfoList) {
regCenter.remove(FailoverNode.getFailoverTaskNodePath(each.toString()));
}
}
/**
* Get task id from failover queue.
*
* @param metaInfo task meta info
* @return failover task id
*/
public Optional<String> getTaskId(final TaskContext.MetaInfo metaInfo) {
String failoverTaskNodePath = FailoverNode.getFailoverTaskNodePath(metaInfo.toString());
Optional<String> result = Optional.absent();
if (regCenter.isExisted(failoverTaskNodePath)) {
result = Optional.of(regCenter.get(failoverTaskNodePath));
}
return result;
}
/**
* Get all failover tasks.
*
* @return all failover tasks
*/
public Map<String, Collection<FailoverTaskInfo>> getAllFailoverTasks() {
if (!regCenter.isExisted(FailoverNode.ROOT)) {
return Collections.emptyMap();
}
List<String> jobNames = regCenter.getChildrenKeys(FailoverNode.ROOT);
Map<String, Collection<FailoverTaskInfo>> result = new HashMap<>(jobNames.size(), 1);
for (String each : jobNames) {
Collection<FailoverTaskInfo> failoverTasks = getFailoverTasks(each);
if (!failoverTasks.isEmpty()) {
result.put(each, failoverTasks);
}
}
return result;
}
/**
* Get failover tasks.
*
* @param jobName job name
* @return collection of failover tasks
*/
private Collection<FailoverTaskInfo> getFailoverTasks(final String jobName) {
List<String> failOverTasks = regCenter.getChildrenKeys(FailoverNode.getFailoverJobNodePath(jobName));
List<FailoverTaskInfo> result = new ArrayList<>(failOverTasks.size());
for (String each : failOverTasks) {
String originalTaskId = regCenter.get(FailoverNode.getFailoverTaskNodePath(each));
if (!Strings.isNullOrEmpty(originalTaskId)) {
result.add(new FailoverTaskInfo(TaskContext.MetaInfo.from(each), originalTaskId));
}
}
return result;
}
}
```
|
```package org.apache.shardingsphere.elasticjob.cloud.event;
import org.apache.shardingsphere.elasticjob.cloud.event.type.JobExecutionEvent;
import org.hamcrest.CoreMatchers;
import org.hamcrest.core.Is;
import org.junit.Assert;
import org.junit.Test;
public final class JobExecutionEventTest {
@Test
public void assertNewJobExecutionEvent() {
JobExecutionEvent actual = new JobExecutionEvent("fake_task_id", "test_job", JobExecutionEvent.ExecutionSource.NORMAL_TRIGGER, 0);
Assert.assertThat(actual.getJobName(), Is.is("test_job"));
Assert.assertThat(actual.getSource(), Is.is(JobExecutionEvent.ExecutionSource.NORMAL_TRIGGER));
Assert.assertThat(actual.getShardingItem(), Is.is(0));
Assert.assertNotNull(actual.getHostname());
Assert.assertNotNull(actual.getStartTime());
Assert.assertNull(actual.getCompleteTime());
Assert.assertFalse(actual.isSuccess());
Assert.assertThat(actual.getFailureCause(), Is.is(""));
}
@Test
public void assertExecutionSuccess() {
JobExecutionEvent startEvent = new JobExecutionEvent("fake_task_id", "test_job", JobExecutionEvent.ExecutionSource.NORMAL_TRIGGER, 0);
JobExecutionEvent successEvent = startEvent.executionSuccess();
Assert.assertNotNull(successEvent.getCompleteTime());
Assert.assertTrue(successEvent.isSuccess());
}
@Test
public void assertExecutionFailure() {
JobExecutionEvent startEvent = new JobExecutionEvent("fake_task_id", "test_job", JobExecutionEvent.ExecutionSource.NORMAL_TRIGGER, 0);
JobExecutionEvent failureEvent = startEvent.executionFailure(new RuntimeException("failure"));
Assert.assertNotNull(failureEvent.getCompleteTime());
Assert.assertFalse(failureEvent.isSuccess());
Assert.assertThat(failureEvent.getFailureCause(), CoreMatchers.startsWith("java.lang.RuntimeException: failure"));
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.shardingsphere.elasticjob.cloud.event.type;
import org.apache.shardingsphere.elasticjob.cloud.exception.ExceptionUtil;
import org.apache.shardingsphere.elasticjob.cloud.event.JobEvent;
import org.apache.shardingsphere.elasticjob.cloud.util.env.IpUtils;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import java.util.Date;
import java.util.UUID;
/**
* Job execution event.
*/
@RequiredArgsConstructor
@AllArgsConstructor
@Getter
public final class JobExecutionEvent implements JobEvent {
private String id = UUID.randomUUID().toString();
private String hostname = IpUtils.getHostName();
private String ip = IpUtils.getIp();
private final String taskId;
private final String jobName;
private final ExecutionSource source;
private final int shardingItem;
private Date startTime = new Date();
@Setter
private Date completeTime;
@Setter
private boolean success;
@Setter
private JobExecutionEventThrowable failureCause;
/**
* Execution success.
*
* @return job execution event
*/
public JobExecutionEvent executionSuccess() {
JobExecutionEvent result = new JobExecutionEvent(id, hostname, ip, taskId, jobName, source, shardingItem, startTime, completeTime, success, failureCause);
result.setCompleteTime(new Date());
result.setSuccess(true);
return result;
}
/**
* execution failure.
*
* @param failureCause failure cause
* @return job execution event
*/
public JobExecutionEvent executionFailure(final Throwable failureCause) {
JobExecutionEvent result = new JobExecutionEvent(id, hostname, ip, taskId, jobName, source, shardingItem, startTime, completeTime, success, new JobExecutionEventThrowable(failureCause));
result.setCompleteTime(new Date());
result.setSuccess(false);
return result;
}
/**
* Get failure cause.
*
* @return failure cause
*/
public String getFailureCause() {
return ExceptionUtil.transform(failureCause == null ? null : failureCause.getThrowable());
}
/**
* Execution source.
*/
public enum ExecutionSource {
NORMAL_TRIGGER, MISFIRE, FAILOVER
}
}
```
|
```package org.apache.shardingsphere.elasticjob.cloud.util.env;
import org.hamcrest.core.Is;
import org.junit.Test;
import java.io.IOException;
import static org.junit.Assert.assertThat;
public final class HostExceptionTest {
@Test
public void assertGetCause() {
IOException cause = new IOException();
assertThat(new HostException(cause).getCause(), Is.<Throwable>is(cause));
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.shardingsphere.elasticjob.cloud.util.env;
import java.io.IOException;
/**
* Host exception.
*/
public final class HostException extends RuntimeException {
private static final long serialVersionUID = 3589264847881174997L;
public HostException(final IOException cause) {
super(cause);
}
}
```
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.fixture;
import org.apache.shardingsphere.elasticjob.cloud.api.simple.SimpleJob;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.config.job.CloudJobConfiguration;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.config.job.CloudJobExecutionType;
import org.apache.shardingsphere.elasticjob.cloud.config.JobCoreConfiguration;
import org.apache.shardingsphere.elasticjob.cloud.config.dataflow.DataflowJobConfiguration;
import org.apache.shardingsphere.elasticjob.cloud.config.script.ScriptJobConfiguration;
import org.apache.shardingsphere.elasticjob.cloud.config.simple.SimpleJobConfiguration;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class CloudJobConfigurationBuilder {
/**
* Create cloud job configuration.
* @param jobName job name
* @return CloudJobConfiguration
*/
public static CloudJobConfiguration createCloudJobConfiguration(final String jobName) {
return new CloudJobConfiguration("test_app",
new SimpleJobConfiguration(JobCoreConfiguration.newBuilder(jobName, "0/30 * * * * ?", 10).failover(true).misfire(true).build(), TestSimpleJob.class.getCanonicalName()),
1.0d, 128.0d, CloudJobExecutionType.TRANSIENT);
}
/**
* Create cloud job configuration.
* @param jobName job name
* @param jobExecutionType execution type
* @return CloudJobConfiguration
*/
public static CloudJobConfiguration createCloudJobConfiguration(final String jobName, final CloudJobExecutionType jobExecutionType) {
return new CloudJobConfiguration("test_app",
new SimpleJobConfiguration(JobCoreConfiguration.newBuilder(jobName, "0/30 * * * * ?", 10).failover(true).misfire(true).build(), TestSimpleJob.class.getCanonicalName()),
1.0d, 128.0d, jobExecutionType);
}
/**
* Create cloud job configuration.
* @param jobName job name
* @param jobExecutionType execution type
* @param shardingTotalCount sharding total count
* @return CloudJobConfiguration
*/
public static CloudJobConfiguration createCloudJobConfiguration(final String jobName, final CloudJobExecutionType jobExecutionType, final int shardingTotalCount) {
return new CloudJobConfiguration("test_app",
new SimpleJobConfiguration(JobCoreConfiguration.newBuilder(jobName, "0/30 * * * * ?", shardingTotalCount).failover(true).misfire(true).build(), TestSimpleJob.class.getCanonicalName()),
1.0d, 128.0d, jobExecutionType);
}
/**
* Create cloud job configuration.
* @param jobName job name
* @param misfire misfire
* @return CloudJobConfiguration
*/
public static CloudJobConfiguration createCloudJobConfiguration(final String jobName, final boolean misfire) {
return new CloudJobConfiguration("test_app",
new SimpleJobConfiguration(JobCoreConfiguration.newBuilder(jobName, "0/30 * * * * ?", 10).failover(true).misfire(misfire).build(), TestSimpleJob.class.getCanonicalName()),
1.0d, 128.0d, CloudJobExecutionType.TRANSIENT);
}
/**
* Create cloud job configuration.
* @param jobName job name
* @param appName app name
* @return CloudJobConfiguration
*/
public static CloudJobConfiguration createCloudJobConfiguration(final String jobName, final String appName) {
return new CloudJobConfiguration(appName,
new SimpleJobConfiguration(JobCoreConfiguration.newBuilder(jobName, "0/30 * * * * ?", 10).failover(true).misfire(true).build(), TestSimpleJob.class.getCanonicalName()),
1.0d, 128.0d, CloudJobExecutionType.TRANSIENT);
}
/**
* Create cloud job configuration.
* @param jobName job name
* @return CloudJobConfiguration
*/
public static CloudJobConfiguration createOtherCloudJobConfiguration(final String jobName) {
return new CloudJobConfiguration("test_app",
new SimpleJobConfiguration(JobCoreConfiguration.newBuilder(jobName, "0/30 * * * * ?", 3).failover(false).misfire(true).build(), TestSimpleJob.class.getCanonicalName()),
1.0d, 128.0d, CloudJobExecutionType.TRANSIENT);
}
/**
* Create cloud job configuration.
* @param jobName job name
* @return CloudJobConfiguration
*/
public static CloudJobConfiguration createCloudSpringJobConfiguration(final String jobName) {
return new CloudJobConfiguration("test_spring_app",
new SimpleJobConfiguration(JobCoreConfiguration.newBuilder(jobName, "0/30 * * * * ?", 10).failover(true).misfire(true).build(), TestSimpleJob.class.getCanonicalName()),
1.0d, 128.0d, CloudJobExecutionType.TRANSIENT, "springSimpleJob", "applicationContext.xml");
}
/**
* Create cloud job configuration.
* @param jobName job name
* @return CloudJobConfiguration
*/
public static CloudJobConfiguration createDataflowCloudJobConfiguration(final String jobName) {
return new CloudJobConfiguration("test_app",
new DataflowJobConfiguration(JobCoreConfiguration.newBuilder(jobName, "0/30 * * * * ?", 3).failover(false).misfire(false).build(), SimpleJob.class.getCanonicalName(), true),
1.0d, 128.0d, CloudJobExecutionType.TRANSIENT);
}
/**
* Create cloud job configuration.
* @param jobName job name
* @return CloudJobConfiguration
*/
public static CloudJobConfiguration createScriptCloudJobConfiguration(final String jobName) {
return createScriptCloudJobConfiguration(jobName, 3);
}
/**
* Create script cloud job configuration.
* @param jobName job name
* @param shardingTotalCount sharding total count
* @return CloudJobConfiguration
*/
public static CloudJobConfiguration createScriptCloudJobConfiguration(final String jobName, final int shardingTotalCount) {
return new CloudJobConfiguration("test_app",
new ScriptJobConfiguration(JobCoreConfiguration.newBuilder(jobName, "0/30 * * * * ?", shardingTotalCount).failover(false).misfire(false).build(), "test.sh"),
1.0d, 128.0d, CloudJobExecutionType.TRANSIENT);
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.shardingsphere.elasticjob.cloud.executor.local;
import org.apache.shardingsphere.elasticjob.cloud.config.JobRootConfiguration;
import org.apache.shardingsphere.elasticjob.cloud.config.JobTypeConfiguration;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
/**
* Local cloud job configuration.
*/
@RequiredArgsConstructor
@AllArgsConstructor
@Getter
public final class LocalCloudJobConfiguration implements JobRootConfiguration {
private final JobTypeConfiguration typeConfig;
private final int shardingItem;
private String beanName;
private String applicationContext;
/**
* Get job name.
*
* @return the job name
*/
public String getJobName() {
return typeConfig.getCoreConfig().getJobName();
}
}
```
|
```package org.apache.shardingsphere.elasticjob.cloud.executor;
import org.apache.shardingsphere.elasticjob.cloud.exception.JobConfigurationException;
import org.apache.shardingsphere.elasticjob.cloud.executor.type.DataflowJobExecutor;
import org.apache.shardingsphere.elasticjob.cloud.fixture.config.TestDataflowJobConfiguration;
import org.apache.shardingsphere.elasticjob.cloud.fixture.config.TestScriptJobConfiguration;
import org.apache.shardingsphere.elasticjob.cloud.fixture.config.TestSimpleJobConfiguration;
import org.apache.shardingsphere.elasticjob.cloud.fixture.job.TestDataflowJob;
import org.apache.shardingsphere.elasticjob.cloud.executor.type.ScriptJobExecutor;
import org.apache.shardingsphere.elasticjob.cloud.executor.type.SimpleJobExecutor;
import org.apache.shardingsphere.elasticjob.cloud.fixture.handler.IgnoreJobExceptionHandler;
import org.apache.shardingsphere.elasticjob.cloud.fixture.job.OtherJob;
import org.apache.shardingsphere.elasticjob.cloud.fixture.job.TestSimpleJob;
import org.hamcrest.CoreMatchers;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public final class JobExecutorFactoryTest {
@Mock
private JobFacade jobFacade;
@Test
public void assertGetJobExecutorForScriptJob() {
Mockito.when(jobFacade.loadJobRootConfiguration(true)).thenReturn(new TestScriptJobConfiguration("test.sh", IgnoreJobExceptionHandler.class));
Assert.assertThat(JobExecutorFactory.getJobExecutor(null, jobFacade), CoreMatchers.instanceOf(ScriptJobExecutor.class));
}
@Test
public void assertGetJobExecutorForSimpleJob() {
Mockito.when(jobFacade.loadJobRootConfiguration(true)).thenReturn(new TestSimpleJobConfiguration());
Assert.assertThat(JobExecutorFactory.getJobExecutor(new TestSimpleJob(null), jobFacade), CoreMatchers.instanceOf(SimpleJobExecutor.class));
}
@Test
public void assertGetJobExecutorForDataflowJob() {
Mockito.when(jobFacade.loadJobRootConfiguration(true)).thenReturn(new TestDataflowJobConfiguration(false));
Assert.assertThat(JobExecutorFactory.getJobExecutor(new TestDataflowJob(null), jobFacade), CoreMatchers.instanceOf(DataflowJobExecutor.class));
}
@Test(expected = JobConfigurationException.class)
public void assertGetJobExecutorWhenJobClassWhenUnsupportedJob() {
JobExecutorFactory.getJobExecutor(new OtherJob(), jobFacade);
}
@Test
public void assertGetJobExecutorTwice() {
Mockito.when(jobFacade.loadJobRootConfiguration(true)).thenReturn(new TestDataflowJobConfiguration(false));
AbstractElasticJobExecutor executor = JobExecutorFactory.getJobExecutor(new TestSimpleJob(null), jobFacade);
AbstractElasticJobExecutor anotherExecutor = JobExecutorFactory.getJobExecutor(new TestSimpleJob(null), jobFacade);
Assert.assertTrue(executor.hashCode() != anotherExecutor.hashCode());
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.shardingsphere.elasticjob.cloud.executor;
import org.apache.shardingsphere.elasticjob.cloud.api.ElasticJob;
import org.apache.shardingsphere.elasticjob.cloud.api.dataflow.DataflowJob;
import org.apache.shardingsphere.elasticjob.cloud.api.simple.SimpleJob;
import org.apache.shardingsphere.elasticjob.cloud.executor.type.DataflowJobExecutor;
import org.apache.shardingsphere.elasticjob.cloud.exception.JobConfigurationException;
import org.apache.shardingsphere.elasticjob.cloud.executor.type.ScriptJobExecutor;
import org.apache.shardingsphere.elasticjob.cloud.executor.type.SimpleJobExecutor;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
/**
* Job executor factory.
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class JobExecutorFactory {
/**
* Get job executor.
*
* @param elasticJob elasticJob object
* @param jobFacade job facade
* @return job executor
*/
@SuppressWarnings("unchecked")
public static AbstractElasticJobExecutor getJobExecutor(final ElasticJob elasticJob, final JobFacade jobFacade) {
if (null == elasticJob) {
return new ScriptJobExecutor(jobFacade);
}
if (elasticJob instanceof SimpleJob) {
return new SimpleJobExecutor((SimpleJob) elasticJob, jobFacade);
}
if (elasticJob instanceof DataflowJob) {
return new DataflowJobExecutor((DataflowJob) elasticJob, jobFacade);
}
throw new JobConfigurationException("Cannot support job type '%s'", elasticJob.getClass().getCanonicalName());
}
}
```
|
```package org.apache.shardingsphere.elasticjob.cloud.fixture;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.apache.shardingsphere.elasticjob.cloud.executor.handler.impl.DefaultExecutorServiceHandler;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class APIJsonConstants {
private static final String JOB_PROPS_JSON = "{\"job_exception_handler\":\"%s\",\"executor_service_handler\":\"" + DefaultExecutorServiceHandler.class.getCanonicalName() + "\"}";
// CHECKSTYLE:OFF
private static final String SIMPLE_JOB_JSON = "{\"jobName\":\"test_job\",\"jobClass\":\"org.apache.shardingsphere.elasticjob.cloud.fixture.job.TestSimpleJob\",\"jobType\":\"SIMPLE\","
+ "\"cron\":\"0/1 * * * * ?\",\"shardingTotalCount\":3,\"shardingItemParameters\":\"0\\u003dA,1\\u003dB,2\\u003dC\",\"jobParameter\":\"param\",\"failover\":true,\"misfire\":false,"
+ "\"description\":\"desc\",\"jobProperties\":%s}";
// CHECKSTYLE:ON
private static final String DATAFLOW_JOB_JSON = "{\"jobName\":\"test_job\",\"jobClass\":\"org.apache.shardingsphere.elasticjob.cloud.fixture.job.TestDataflowJob\",\"jobType\":\"DATAFLOW\","
+ "\"cron\":\"0/1 * * * * ?\",\"shardingTotalCount\":3,\"shardingItemParameters\":\"\",\"jobParameter\":\"\",\"failover\":false,\"misfire\":true,\"description\":\"\","
+ "\"jobProperties\":%s,\"streamingProcess\":true}";
private static final String SCRIPT_JOB_JSON = "{\"jobName\":\"test_job\",\"jobClass\":\"org.apache.shardingsphere.elasticjob.cloud.api.script.ScriptJob\",\"jobType\":\"SCRIPT\","
+ "\"cron\":\"0/1 * * * * ?\",\"shardingTotalCount\":3,\"shardingItemParameters\":\"\",\"jobParameter\":\"\",\"failover\":false,\"misfire\":true,\"description\":\"\","
+ "\"jobProperties\":%s,\"scriptCommandLine\":\"test.sh\"}";
/**
* Get job properties in json format.
* @param jobExceptionHandler the job exception handler
* @return the json string
*/
public static String getJobPropertiesJson(final String jobExceptionHandler) {
return String.format(JOB_PROPS_JSON, jobExceptionHandler);
}
/**
* Get simple job in json format.
* @param jobExceptionHandler the job exception handler
* @return the json string
*/
public static String getSimpleJobJson(final String jobExceptionHandler) {
return String.format(SIMPLE_JOB_JSON, getJobPropertiesJson(jobExceptionHandler));
}
/**
* Get dataflow job in json format.
* @param jobExceptionHandler the job exception handler
* @return the json string
*/
public static String getDataflowJobJson(final String jobExceptionHandler) {
return String.format(DATAFLOW_JOB_JSON, getJobPropertiesJson(jobExceptionHandler));
}
/**
* Get script job in json format.
* @param jobExceptionHandler the job exception handler
* @return the json string
*/
public static String getScriptJobJson(final String jobExceptionHandler) {
return String.format(SCRIPT_JOB_JSON, getJobPropertiesJson(jobExceptionHandler));
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.config.constants;
/**
* Cloud configuration constants.
*/
public final class CloudConfigurationConstants {
public static final String APP_NAME = "appName";
public static final String BOOTSTRAP_SCRIPT = "bootstrapScript";
public static final String APP_CACHE_ENABLE = "appCacheEnable";
public static final String APP_URL = "appURL";
public static final String EVENT_TRACE_SAMPLING_COUNT = "eventTraceSamplingCount";
public static final String CPU_COUNT = "cpuCount";
public static final String MEMORY_MB = "memoryMB";
public static final String JOB_EXECUTION_TYPE = "jobExecutionType";
public static final String BEAN_NAME = "beanName";
public static final String APPLICATION_CONTEXT = "applicationContext";
}
```
|
```package org.apache.shardingsphere.elasticjob.cloud.fixture.job;
import org.apache.shardingsphere.elasticjob.cloud.api.ShardingContext;
import org.apache.shardingsphere.elasticjob.cloud.api.simple.SimpleJob;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
public final class TestSimpleJob implements SimpleJob {
private final JobCaller jobCaller;
@Override
public void execute(final ShardingContext shardingContext) {
jobCaller.execute();
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.shardingsphere.elasticjob.cloud.api.simple;
import org.apache.shardingsphere.elasticjob.cloud.api.ElasticJob;
import org.apache.shardingsphere.elasticjob.cloud.api.ShardingContext;
/**
* Simple job.
*/
public interface SimpleJob extends ElasticJob {
/**
* Execute job.
*
* @param shardingContext sharding context
*/
void execute(ShardingContext shardingContext);
}
```
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.producer;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.config.app.CloudAppConfigurationService;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.config.job.CloudJobConfiguration;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.config.job.CloudJobConfigurationService;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.config.job.CloudJobExecutionType;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.fixture.CloudAppConfigurationBuilder;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.fixture.CloudJobConfigurationBuilder;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.state.disable.job.DisableJobService;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.state.running.RunningService;
import org.apache.shardingsphere.elasticjob.cloud.exception.AppConfigurationException;
import org.apache.shardingsphere.elasticjob.cloud.exception.JobConfigurationException;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.config.app.CloudAppConfiguration;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.state.ready.ReadyService;
import org.apache.shardingsphere.elasticjob.cloud.context.TaskContext;
import org.apache.shardingsphere.elasticjob.cloud.reg.base.CoordinatorRegistryCenter;
import com.google.common.base.Optional;
import com.google.common.collect.Lists;
import org.apache.mesos.Protos;
import org.apache.mesos.SchedulerDriver;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.unitils.util.ReflectionUtils;
import java.util.Arrays;
import java.util.List;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public final class ProducerManagerTest {
@Mock
private SchedulerDriver schedulerDriver;
@Mock
private CoordinatorRegistryCenter regCenter;
@Mock
private CloudAppConfigurationService appConfigService;
@Mock
private CloudJobConfigurationService configService;
@Mock
private ReadyService readyService;
@Mock
private RunningService runningService;
@Mock
private DisableJobService disableJobService;
@Mock
private TransientProducerScheduler transientProducerScheduler;
private ProducerManager producerManager;
private final CloudAppConfiguration appConfig = CloudAppConfigurationBuilder.createCloudAppConfiguration("test_app");
private final CloudJobConfiguration transientJobConfig = CloudJobConfigurationBuilder.createCloudJobConfiguration("transient_test_job");
private final CloudJobConfiguration daemonJobConfig = CloudJobConfigurationBuilder.createCloudJobConfiguration("daemon_test_job", CloudJobExecutionType.DAEMON);
@Before
public void setUp() throws NoSuchFieldException {
producerManager = new ProducerManager(schedulerDriver, regCenter);
ReflectionUtils.setFieldValue(producerManager, "appConfigService", appConfigService);
ReflectionUtils.setFieldValue(producerManager, "configService", configService);
ReflectionUtils.setFieldValue(producerManager, "readyService", readyService);
ReflectionUtils.setFieldValue(producerManager, "runningService", runningService);
ReflectionUtils.setFieldValue(producerManager, "disableJobService", disableJobService);
ReflectionUtils.setFieldValue(producerManager, "transientProducerScheduler", transientProducerScheduler);
}
@Test
public void assertStartup() {
when(configService.loadAll()).thenReturn(Arrays.asList(transientJobConfig, daemonJobConfig));
producerManager.startup();
verify(configService).loadAll();
verify(transientProducerScheduler).register(transientJobConfig);
verify(readyService).addDaemon("daemon_test_job");
}
@Test(expected = AppConfigurationException.class)
public void assertRegisterJobWithoutApp() {
when(appConfigService.load("test_app")).thenReturn(Optional.<CloudAppConfiguration>absent());
producerManager.register(transientJobConfig);
}
@Test(expected = JobConfigurationException.class)
public void assertRegisterExistedJob() {
when(appConfigService.load("test_app")).thenReturn(Optional.of(appConfig));
when(configService.load("transient_test_job")).thenReturn(Optional.of(transientJobConfig));
producerManager.register(transientJobConfig);
}
@Test(expected = JobConfigurationException.class)
public void assertRegisterDisabledJob() {
when(disableJobService.isDisabled("transient_test_job")).thenReturn(true);
producerManager.register(transientJobConfig);
}
@Test
public void assertRegisterTransientJob() {
when(appConfigService.load("test_app")).thenReturn(Optional.of(appConfig));
when(configService.load("transient_test_job")).thenReturn(Optional.<CloudJobConfiguration>absent());
producerManager.register(transientJobConfig);
verify(configService).add(transientJobConfig);
verify(transientProducerScheduler).register(transientJobConfig);
}
@Test
public void assertRegisterDaemonJob() {
when(appConfigService.load("test_app")).thenReturn(Optional.of(appConfig));
when(configService.load("daemon_test_job")).thenReturn(Optional.<CloudJobConfiguration>absent());
producerManager.register(daemonJobConfig);
verify(configService).add(daemonJobConfig);
verify(readyService).addDaemon("daemon_test_job");
}
@Test(expected = JobConfigurationException.class)
public void assertUpdateNotExisted() {
when(configService.load("transient_test_job")).thenReturn(Optional.<CloudJobConfiguration>absent());
producerManager.update(transientJobConfig);
}
@Test
public void assertUpdateExisted() {
when(configService.load("transient_test_job")).thenReturn(Optional.of(transientJobConfig));
List<TaskContext> taskContexts = Arrays.asList(
TaskContext.from("transient_test_job@-@0@-@READY@-@SLAVE-S0@-@UUID"), TaskContext.from("transient_test_job@-@1@-@READY@-@SLAVE-S0@-@UUID"));
when(runningService.getRunningTasks("transient_test_job")).thenReturn(taskContexts);
producerManager.update(transientJobConfig);
verify(configService).update(transientJobConfig);
for (TaskContext each : taskContexts) {
verify(schedulerDriver).killTask(Protos.TaskID.newBuilder().setValue(each.getId()).build());
}
verify(runningService).remove("transient_test_job");
verify(readyService).remove(Lists.newArrayList("transient_test_job"));
}
@Test
public void assertDeregisterNotExisted() {
when(configService.load("transient_test_job")).thenReturn(Optional.<CloudJobConfiguration>absent());
producerManager.deregister("transient_test_job");
verify(configService, times(0)).remove("transient_test_job");
}
@Test
public void assertDeregisterExisted() {
when(configService.load("transient_test_job")).thenReturn(Optional.of(transientJobConfig));
List<TaskContext> taskContexts = Arrays.asList(
TaskContext.from("transient_test_job@-@0@-@READY@-@SLAVE-S0@-@UUID"), TaskContext.from("transient_test_job@-@1@-@READY@-@SLAVE-S0@-@UUID"));
when(runningService.getRunningTasks("transient_test_job")).thenReturn(taskContexts);
producerManager.deregister("transient_test_job");
for (TaskContext each : taskContexts) {
verify(schedulerDriver).killTask(Protos.TaskID.newBuilder().setValue(each.getId()).build());
}
verify(disableJobService).remove("transient_test_job");
verify(configService).remove("transient_test_job");
verify(runningService).remove("transient_test_job");
verify(readyService).remove(Lists.newArrayList("transient_test_job"));
}
@Test
public void assertShutdown() {
producerManager.shutdown();
verify(transientProducerScheduler).shutdown();
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.producer;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.config.app.CloudAppConfigurationService;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.config.job.CloudJobConfiguration;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.config.job.CloudJobConfigurationService;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.config.job.CloudJobExecutionType;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.state.disable.app.DisableAppService;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.state.disable.job.DisableJobService;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.state.running.RunningService;
import org.apache.shardingsphere.elasticjob.cloud.exception.AppConfigurationException;
import org.apache.shardingsphere.elasticjob.cloud.exception.JobConfigurationException;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.config.app.CloudAppConfiguration;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.state.ready.ReadyService;
import org.apache.shardingsphere.elasticjob.cloud.context.TaskContext;
import org.apache.shardingsphere.elasticjob.cloud.reg.base.CoordinatorRegistryCenter;
import com.google.common.base.Optional;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.mesos.Protos;
import org.apache.mesos.Protos.ExecutorID;
import org.apache.mesos.Protos.SlaveID;
import org.apache.mesos.SchedulerDriver;
/**
* Producer manager.
*/
@Slf4j
public final class ProducerManager {
private final CloudAppConfigurationService appConfigService;
private final CloudJobConfigurationService configService;
private final ReadyService readyService;
private final RunningService runningService;
private final DisableAppService disableAppService;
private final DisableJobService disableJobService;
private final TransientProducerScheduler transientProducerScheduler;
private final SchedulerDriver schedulerDriver;
public ProducerManager(final SchedulerDriver schedulerDriver, final CoordinatorRegistryCenter regCenter) {
this.schedulerDriver = schedulerDriver;
appConfigService = new CloudAppConfigurationService(regCenter);
configService = new CloudJobConfigurationService(regCenter);
readyService = new ReadyService(regCenter);
runningService = new RunningService(regCenter);
disableAppService = new DisableAppService(regCenter);
disableJobService = new DisableJobService(regCenter);
transientProducerScheduler = new TransientProducerScheduler(readyService);
}
/**
* Start the producer manager.
*/
public void startup() {
log.info("Start producer manager");
transientProducerScheduler.start();
for (CloudJobConfiguration each : configService.loadAll()) {
schedule(each);
}
}
/**
* Register the job.
*
* @param jobConfig cloud job config
*/
public void register(final CloudJobConfiguration jobConfig) {
if (disableJobService.isDisabled(jobConfig.getJobName())) {
throw new JobConfigurationException("Job '%s' has been disable.", jobConfig.getJobName());
}
Optional<CloudAppConfiguration> appConfigFromZk = appConfigService.load(jobConfig.getAppName());
if (!appConfigFromZk.isPresent()) {
throw new AppConfigurationException("Register app '%s' firstly.", jobConfig.getAppName());
}
Optional<CloudJobConfiguration> jobConfigFromZk = configService.load(jobConfig.getJobName());
if (jobConfigFromZk.isPresent()) {
throw new JobConfigurationException("Job '%s' already existed.", jobConfig.getJobName());
}
configService.add(jobConfig);
schedule(jobConfig);
}
/**
* Update the job.
*
* @param jobConfig cloud job config
*/
public void update(final CloudJobConfiguration jobConfig) {
Optional<CloudJobConfiguration> jobConfigFromZk = configService.load(jobConfig.getJobName());
if (!jobConfigFromZk.isPresent()) {
throw new JobConfigurationException("Cannot found job '%s', please register first.", jobConfig.getJobName());
}
configService.update(jobConfig);
reschedule(jobConfig.getJobName());
}
/**
* Deregister the job.
*
* @param jobName job name
*/
public void deregister(final String jobName) {
Optional<CloudJobConfiguration> jobConfig = configService.load(jobName);
if (jobConfig.isPresent()) {
disableJobService.remove(jobName);
configService.remove(jobName);
}
unschedule(jobName);
}
/**
* Schedule the job.
*
* @param jobConfig cloud job config
*/
public void schedule(final CloudJobConfiguration jobConfig) {
if (disableAppService.isDisabled(jobConfig.getAppName()) || disableJobService.isDisabled(jobConfig.getJobName())) {
return;
}
if (CloudJobExecutionType.TRANSIENT == jobConfig.getJobExecutionType()) {
transientProducerScheduler.register(jobConfig);
} else if (CloudJobExecutionType.DAEMON == jobConfig.getJobExecutionType()) {
readyService.addDaemon(jobConfig.getJobName());
}
}
/**
* Stop to schedule the job.
*
* @param jobName job name
*/
public void unschedule(final String jobName) {
for (TaskContext each : runningService.getRunningTasks(jobName)) {
schedulerDriver.killTask(Protos.TaskID.newBuilder().setValue(each.getId()).build());
}
runningService.remove(jobName);
readyService.remove(Lists.newArrayList(jobName));
Optional<CloudJobConfiguration> jobConfig = configService.load(jobName);
if (jobConfig.isPresent()) {
transientProducerScheduler.deregister(jobConfig.get());
}
}
/**
* Re-schedule the job.
*
* @param jobName job name
*/
public void reschedule(final String jobName) {
unschedule(jobName);
Optional<CloudJobConfiguration> jobConfig = configService.load(jobName);
if (jobConfig.isPresent()) {
schedule(jobConfig.get());
}
}
/**
* Send message to executor.
*
* @param executorId the executor of which to receive message
* @param slaveId the slave id of the executor
* @param data message content
*/
public void sendFrameworkMessage(final ExecutorID executorId, final SlaveID slaveId, final byte[] data) {
schedulerDriver.sendFrameworkMessage(executorId, slaveId, data);
}
/**
* Shutdown the producer manager.
*/
public void shutdown() {
log.info("Stop producer manager");
transientProducerScheduler.shutdown();
}
}
```
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.mesos;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.fixture.CloudJobConfigurationBuilder;
import org.apache.shardingsphere.elasticjob.cloud.context.ExecutionType;
import org.apache.shardingsphere.elasticjob.cloud.context.TaskContext;
import com.netflix.fenzo.TaskRequest;
import org.hamcrest.core.Is;
import org.hamcrest.core.StringStartsWith;
import org.junit.Assert;
import org.junit.Test;
import java.util.Collections;
public final class JobTaskRequestTest {
private final JobTaskRequest jobTaskRequest =
new JobTaskRequest(new TaskContext("test_job", Collections.singletonList(0), ExecutionType
.READY, "unassigned-slave"), CloudJobConfigurationBuilder.createCloudJobConfiguration("test_job"));
@Test
public void assertGetId() {
Assert.assertThat(jobTaskRequest.getId(), StringStartsWith.startsWith("test_job@-@0@-@READY@-@unassigned-slave"));
}
@Test
public void assertTaskGroupName() {
Assert.assertThat(jobTaskRequest.taskGroupName(), Is.is(""));
}
@Test
public void assertGetCPUs() {
Assert.assertThat(jobTaskRequest.getCPUs(), Is.is(1.0d));
}
@Test
public void assertGetMemory() {
Assert.assertThat(jobTaskRequest.getMemory(), Is.is(128.0d));
}
@Test
public void assertGetNetworkMbps() {
Assert.assertThat(jobTaskRequest.getNetworkMbps(), Is.is(0d));
}
@Test
public void assertGetDisk() {
Assert.assertThat(jobTaskRequest.getDisk(), Is.is(10d));
}
@Test
public void assertGetPorts() {
Assert.assertThat(jobTaskRequest.getPorts(), Is.is(1));
}
@Test
public void assertGetScalarRequests() {
Assert.assertNull(jobTaskRequest.getScalarRequests());
}
@Test
public void assertGetHardConstraints() {
AppConstraintEvaluator.init(null);
Assert.assertThat(jobTaskRequest.getHardConstraints().size(), Is.is(1));
}
@Test
public void assertGetSoftConstraints() {
Assert.assertNull(jobTaskRequest.getSoftConstraints());
}
@Test
public void assertSetAssignedResources() {
jobTaskRequest.setAssignedResources(null);
}
@Test
public void assertGetAssignedResources() {
Assert.assertNull(jobTaskRequest.getAssignedResources());
}
@Test
public void assertGetCustomNamedResources() {
Assert.assertThat(jobTaskRequest.getCustomNamedResources(), Is.is(Collections.<String, TaskRequest.NamedResourceSetRequest>emptyMap()));
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.mesos;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.config.job.CloudJobConfiguration;
import org.apache.shardingsphere.elasticjob.cloud.context.TaskContext;
import com.netflix.fenzo.ConstraintEvaluator;
import com.netflix.fenzo.TaskRequest;
import com.netflix.fenzo.VMTaskFitnessCalculator;
import lombok.RequiredArgsConstructor;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* Job task request.
*/
@RequiredArgsConstructor
public final class JobTaskRequest implements TaskRequest {
private final TaskContext taskContext;
private final CloudJobConfiguration jobConfig;
@Override
public String getId() {
return taskContext.getId();
}
@Override
public String taskGroupName() {
return "";
}
@Override
public double getCPUs() {
return jobConfig.getCpuCount();
}
@Override
public double getMemory() {
return jobConfig.getMemoryMB();
}
@Override
public double getNetworkMbps() {
return 0;
}
@Override
public double getDisk() {
return 10d;
}
@Override
public int getPorts() {
return 1;
}
@Override
public Map<String, Double> getScalarRequests() {
return null;
}
@Override
public List<? extends ConstraintEvaluator> getHardConstraints() {
return Collections.singletonList(AppConstraintEvaluator.getInstance());
}
@Override
public List<? extends VMTaskFitnessCalculator> getSoftConstraints() {
return null;
}
@Override
public void setAssignedResources(final AssignedResources assignedResources) {
}
@Override
public AssignedResources getAssignedResources() {
return null;
}
@Override
public Map<String, NamedResourceSetRequest> getCustomNamedResources() {
return Collections.emptyMap();
}
}
```
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.state.ready;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.fixture.CloudJobConfigurationBuilder;
import org.apache.shardingsphere.elasticjob.cloud.context.ExecutionType;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.config.job.CloudJobConfiguration;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.config.job.CloudJobConfigurationService;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.config.job.CloudJobExecutionType;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.context.JobContext;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.env.BootstrapEnvironment;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.state.running.RunningService;
import org.apache.shardingsphere.elasticjob.cloud.reg.base.CoordinatorRegistryCenter;
import com.google.common.base.Optional;
import com.google.common.collect.Lists;
import org.hamcrest.core.Is;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentMatchers;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.unitils.util.ReflectionUtils;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
@RunWith(MockitoJUnitRunner.class)
public final class ReadyServiceTest {
@Mock
private CoordinatorRegistryCenter regCenter;
@Mock
private CloudJobConfigurationService configService;
@Mock
private RunningService runningService;
@Mock
private List<String> mockedReadyQueue;
private ReadyService readyService;
@Before
public void setUp() throws NoSuchFieldException {
readyService = new ReadyService(regCenter);
ReflectionUtils.setFieldValue(readyService, "configService", configService);
ReflectionUtils.setFieldValue(readyService, "runningService", runningService);
}
@Test
public void assertAddTransientWithJobConfigIsNotPresent() {
Mockito.when(configService.load("test_job")).thenReturn(Optional.<CloudJobConfiguration>absent());
readyService.addTransient("test_job");
Mockito.verify(regCenter, Mockito.times(0)).isExisted("/state/ready");
Mockito.verify(regCenter, Mockito.times(0)).persist((String) ArgumentMatchers.any(), ArgumentMatchers.eq(""));
}
@Test
public void assertAddTransientWithJobConfigIsNotTransient() {
Mockito.when(configService.load("test_job")).thenReturn(Optional.of(CloudJobConfigurationBuilder.createCloudJobConfiguration("test_job", CloudJobExecutionType.DAEMON)));
readyService.addTransient("test_job");
Mockito.verify(regCenter, Mockito.times(0)).isExisted("/state/ready");
Mockito.verify(regCenter, Mockito.times(0)).persist((String) ArgumentMatchers.any(), ArgumentMatchers.eq(""));
}
@Test
public void assertAddTransientWhenJobExistedAndEnableMisfired() {
Mockito.when(configService.load("test_job")).thenReturn(Optional.of(CloudJobConfigurationBuilder.createCloudJobConfiguration("test_job")));
Mockito.when(regCenter.getDirectly("/state/ready/test_job")).thenReturn("1");
readyService.addTransient("test_job");
Mockito.verify(regCenter).persist("/state/ready/test_job", "2");
}
@Test
public void assertAddTransientWhenJobExistedAndDisableMisfired() {
Mockito.when(configService.load("test_job")).thenReturn(Optional.of(CloudJobConfigurationBuilder.createCloudJobConfiguration("test_job", false)));
Mockito.when(regCenter.getDirectly("/state/ready/test_job")).thenReturn("1");
readyService.addTransient("test_job");
Mockito.verify(regCenter).persist("/state/ready/test_job", "1");
}
@Test
public void assertAddTransientWhenJobNotExisted() {
Mockito.when(configService.load("test_job")).thenReturn(Optional.of(CloudJobConfigurationBuilder.createCloudJobConfiguration("test_job")));
readyService.addTransient("test_job");
Mockito.verify(regCenter).persist("/state/ready/test_job", "1");
}
@Test
public void assertAddTransientWithOverJobQueueSize() {
Mockito.when(regCenter.getNumChildren(ReadyNode.ROOT)).thenReturn(BootstrapEnvironment.getInstance().getFrameworkConfiguration().getJobStateQueueSize() + 1);
readyService.addTransient("test_job");
Mockito.verify(regCenter, Mockito.times(0)).persist("/state/ready/test_job", "1");
}
@Test
public void assertAddDaemonWithOverJobQueueSize() {
Mockito.when(regCenter.getNumChildren(ReadyNode.ROOT)).thenReturn(BootstrapEnvironment.getInstance().getFrameworkConfiguration().getJobStateQueueSize() + 1);
readyService.addDaemon("test_job");
Mockito.verify(regCenter, Mockito.times(0)).persist("/state/ready/test_job", "1");
}
@Test
public void assertAddDaemonWithJobConfigIsNotPresent() {
Mockito.when(configService.load("test_job")).thenReturn(Optional.<CloudJobConfiguration>absent());
readyService.addDaemon("test_job");
Mockito.verify(regCenter, Mockito.times(0)).isExisted("/state/ready");
Mockito.verify(regCenter, Mockito.times(0)).persist((String) ArgumentMatchers.any(), ArgumentMatchers.eq("1"));
}
@Test
public void assertAddDaemonWithJobConfigIsNotDaemon() {
Mockito.when(configService.load("test_job")).thenReturn(Optional.of(CloudJobConfigurationBuilder.createCloudJobConfiguration("test_job")));
readyService.addDaemon("test_job");
Mockito.verify(regCenter, Mockito.times(0)).isExisted("/state/ready");
Mockito.verify(regCenter, Mockito.times(0)).persist((String) ArgumentMatchers.any(), ArgumentMatchers.eq("1"));
}
@Test
public void assertAddDaemonWithoutRootNode() {
Mockito.when(configService.load("test_job")).thenReturn(Optional.of(CloudJobConfigurationBuilder.createCloudJobConfiguration("test_job", CloudJobExecutionType.DAEMON)));
readyService.addDaemon("test_job");
Mockito.verify(regCenter).persist("/state/ready/test_job", "1");
}
@Test
public void assertAddDaemonWithSameJobName() {
Mockito.when(configService.load("test_job")).thenReturn(Optional.of(CloudJobConfigurationBuilder.createCloudJobConfiguration("test_job", CloudJobExecutionType.DAEMON)));
readyService.addDaemon("test_job");
Mockito.verify(regCenter).persist((String) ArgumentMatchers.any(), ArgumentMatchers.eq("1"));
}
@Test
public void assertAddRunningDaemon() {
Mockito.when(configService.load("test_job")).thenReturn(Optional.of(CloudJobConfigurationBuilder.createCloudJobConfiguration("test_job", CloudJobExecutionType.DAEMON)));
Mockito.when(runningService.isJobRunning("test_job")).thenReturn(true);
readyService.addDaemon("test_job");
Mockito.verify(regCenter, Mockito.never()).persist((String) ArgumentMatchers.any(), ArgumentMatchers.eq("1"));
}
@Test
public void assertAddDaemonWithoutSameJobName() {
Mockito.when(configService.load("test_job")).thenReturn(Optional.of(CloudJobConfigurationBuilder.createCloudJobConfiguration("test_job", CloudJobExecutionType.DAEMON)));
readyService.addDaemon("test_job");
Mockito.verify(regCenter).persist("/state/ready/test_job", "1");
}
@Test
public void assertGetAllEligibleJobContextsWithoutRootNode() {
Mockito.when(regCenter.isExisted("/state/ready")).thenReturn(false);
Assert.assertTrue(readyService.getAllEligibleJobContexts(Collections.<JobContext>emptyList()).isEmpty());
Mockito.verify(regCenter).isExisted("/state/ready");
}
@Test
public void assertSetMisfireDisabledWhenJobIsNotExisted() {
Mockito.when(configService.load("test_job")).thenReturn(Optional.<CloudJobConfiguration>absent());
readyService.setMisfireDisabled("test_job");
Mockito.verify(regCenter, Mockito.times(0)).persist("/state/ready/test_job", "1");
}
@Test
public void assertSetMisfireDisabledWhenReadyNodeNotExisted() {
Mockito.when(configService.load("test_job")).thenReturn(Optional.of(CloudJobConfigurationBuilder.createCloudJobConfiguration("test_job")));
readyService.setMisfireDisabled("test_job");
Mockito.verify(regCenter, Mockito.times(0)).persist("/state/ready/test_job", "1");
}
@Test
public void assertSetMisfireDisabledWhenReadyNodeExisted() {
Mockito.when(configService.load("test_job")).thenReturn(Optional.of(CloudJobConfigurationBuilder.createCloudJobConfiguration("test_job")));
Mockito.when(regCenter.getDirectly("/state/ready/test_job")).thenReturn("100");
readyService.setMisfireDisabled("test_job");
Mockito.verify(regCenter).persist("/state/ready/test_job", "1");
}
@Test
public void assertGetAllEligibleJobContextsWithRootNode() {
Mockito.when(regCenter.isExisted("/state/ready")).thenReturn(true);
Mockito.when(regCenter.getChildrenKeys("/state/ready")).thenReturn(Arrays.asList("not_existed_job", "running_job", "ineligible_job", "eligible_job"));
Mockito.when(configService.load("not_existed_job")).thenReturn(Optional.<CloudJobConfiguration>absent());
Mockito.when(configService.load("running_job")).thenReturn(Optional.of(CloudJobConfigurationBuilder.createCloudJobConfiguration("running_job")));
Mockito.when(configService.load("eligible_job")).thenReturn(Optional.of(CloudJobConfigurationBuilder.createCloudJobConfiguration("eligible_job")));
Mockito.when(runningService.isJobRunning("running_job")).thenReturn(true);
Mockito.when(runningService.isJobRunning("eligible_job")).thenReturn(false);
Assert.assertThat(readyService.getAllEligibleJobContexts(Collections.singletonList(
JobContext.from(CloudJobConfigurationBuilder.createCloudJobConfiguration("ineligible_job"), ExecutionType.READY))).size(), Is.is(1));
Mockito.verify(regCenter).isExisted("/state/ready");
Mockito.verify(regCenter, Mockito.times(1)).getChildrenKeys("/state/ready");
Mockito.verify(configService).load("not_existed_job");
Mockito.verify(configService).load("running_job");
Mockito.verify(configService).load("eligible_job");
Mockito.verify(regCenter).remove("/state/ready/not_existed_job");
}
@Test
public void assertGetAllEligibleJobContextsWithRootNodeAndDaemonJob() {
Mockito.when(regCenter.isExisted("/state/ready")).thenReturn(true);
Mockito.when(regCenter.getChildrenKeys("/state/ready")).thenReturn(Arrays.asList("not_existed_job", "running_job"));
Mockito.when(configService.load("not_existed_job")).thenReturn(Optional.<CloudJobConfiguration>absent());
Mockito.when(configService.load("running_job")).thenReturn(Optional.of(CloudJobConfigurationBuilder.createCloudJobConfiguration("running_job", CloudJobExecutionType.DAEMON)));
Mockito.when(runningService.isJobRunning("running_job")).thenReturn(true);
Assert.assertThat(readyService.getAllEligibleJobContexts(Collections.<JobContext>emptyList()).size(), Is.is(0));
Mockito.verify(regCenter).isExisted("/state/ready");
Mockito.verify(regCenter, Mockito.times(1)).getChildrenKeys("/state/ready");
Mockito.verify(configService).load("not_existed_job");
Mockito.verify(configService).load("running_job");
}
@Test
public void assertRemove() {
Mockito.when(regCenter.getDirectly("/state/ready/test_job_1")).thenReturn("1");
Mockito.when(regCenter.getDirectly("/state/ready/test_job_2")).thenReturn("2");
readyService.remove(Arrays.asList("test_job_1", "test_job_2"));
Mockito.verify(regCenter).persist("/state/ready/test_job_2", "1");
Mockito.verify(regCenter).remove("/state/ready/test_job_1");
Mockito.verify(regCenter, Mockito.times(0)).persist("/state/ready/test_job_1", "0");
Mockito.verify(regCenter, Mockito.times(0)).remove("/state/ready/test_job_2");
}
@Test
public void assertGetAllTasksWithoutRootNode() {
Mockito.when(regCenter.isExisted(ReadyNode.ROOT)).thenReturn(false);
Assert.assertTrue(readyService.getAllReadyTasks().isEmpty());
Mockito.verify(regCenter).isExisted(ReadyNode.ROOT);
Mockito.verify(regCenter, Mockito.times(0)).getChildrenKeys((String) ArgumentMatchers.any());
Mockito.verify(regCenter, Mockito.times(0)).get((String) ArgumentMatchers.any());
}
@Test
public void assertGetAllTasksWhenRootNodeHasNoChild() {
Mockito.when(regCenter.isExisted(ReadyNode.ROOT)).thenReturn(true);
Mockito.when(regCenter.getChildrenKeys(ReadyNode.ROOT)).thenReturn(Collections.<String>emptyList());
Assert.assertTrue(readyService.getAllReadyTasks().isEmpty());
Mockito.verify(regCenter).isExisted(ReadyNode.ROOT);
Mockito.verify(regCenter).getChildrenKeys(ReadyNode.ROOT);
Mockito.verify(regCenter, Mockito.times(0)).get((String) ArgumentMatchers.any());
}
@Test
public void assertGetAllTasksWhenNodeIsEmpty() {
Mockito.when(regCenter.isExisted(ReadyNode.ROOT)).thenReturn(true);
Mockito.when(regCenter.getChildrenKeys(ReadyNode.ROOT)).thenReturn(Lists.newArrayList("test_job"));
Mockito.when(regCenter.get(ReadyNode.getReadyJobNodePath("test_job"))).thenReturn("");
Assert.assertTrue(readyService.getAllReadyTasks().isEmpty());
Mockito.verify(regCenter).isExisted(ReadyNode.ROOT);
Mockito.verify(regCenter).getChildrenKeys(ReadyNode.ROOT);
Mockito.verify(regCenter).get(ReadyNode.getReadyJobNodePath("test_job"));
}
@Test
public void assertGetAllTasksWithRootNode() {
Mockito.when(regCenter.isExisted(ReadyNode.ROOT)).thenReturn(true);
Mockito.when(regCenter.getChildrenKeys(ReadyNode.ROOT)).thenReturn(Lists.newArrayList("test_job_1", "test_job_2"));
Mockito.when(regCenter.get(ReadyNode.getReadyJobNodePath("test_job_1"))).thenReturn("1");
Mockito.when(regCenter.get(ReadyNode.getReadyJobNodePath("test_job_2"))).thenReturn("5");
Map<String, Integer> result = readyService.getAllReadyTasks();
Assert.assertThat(result.size(), Is.is(2));
Assert.assertThat(result.get("test_job_1"), Is.is(1));
Assert.assertThat(result.get("test_job_2"), Is.is(5));
Mockito.verify(regCenter).isExisted(ReadyNode.ROOT);
Mockito.verify(regCenter).getChildrenKeys(ReadyNode.ROOT);
Mockito.verify(regCenter, Mockito.times(2)).get((String) ArgumentMatchers.any());
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.state.ready;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.config.job.CloudJobConfiguration;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.config.job.CloudJobConfigurationService;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.config.job.CloudJobExecutionType;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.context.JobContext;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.env.BootstrapEnvironment;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.state.running.RunningService;
import org.apache.shardingsphere.elasticjob.cloud.context.ExecutionType;
import org.apache.shardingsphere.elasticjob.cloud.reg.base.CoordinatorRegistryCenter;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Strings;
import com.google.common.collect.Collections2;
import lombok.extern.slf4j.Slf4j;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Ready service.
*/
@Slf4j
public final class ReadyService {
private final BootstrapEnvironment env = BootstrapEnvironment.getInstance();
private final CoordinatorRegistryCenter regCenter;
private final CloudJobConfigurationService configService;
private final RunningService runningService;
public ReadyService(final CoordinatorRegistryCenter regCenter) {
this.regCenter = regCenter;
configService = new CloudJobConfigurationService(regCenter);
runningService = new RunningService(regCenter);
}
/**
* Add transient job to ready queue.
*
* @param jobName job name
*/
public void addTransient(final String jobName) {
if (regCenter.getNumChildren(ReadyNode.ROOT) > env.getFrameworkConfiguration().getJobStateQueueSize()) {
log.warn("Cannot add transient job, caused by read state queue size is larger than {}.", env.getFrameworkConfiguration().getJobStateQueueSize());
return;
}
Optional<CloudJobConfiguration> cloudJobConfig = configService.load(jobName);
if (!cloudJobConfig.isPresent() || CloudJobExecutionType.TRANSIENT != cloudJobConfig.get().getJobExecutionType()) {
return;
}
String readyJobNode = ReadyNode.getReadyJobNodePath(jobName);
String times = regCenter.getDirectly(readyJobNode);
if (cloudJobConfig.get().getTypeConfig().getCoreConfig().isMisfire()) {
regCenter.persist(readyJobNode, Integer.toString(null == times ? 1 : Integer.parseInt(times) + 1));
} else {
regCenter.persist(ReadyNode.getReadyJobNodePath(jobName), "1");
}
}
/**
* Add daemon job to ready queue.
*
* @param jobName job name
*/
public void addDaemon(final String jobName) {
if (regCenter.getNumChildren(ReadyNode.ROOT) > env.getFrameworkConfiguration().getJobStateQueueSize()) {
log.warn("Cannot add daemon job, caused by read state queue size is larger than {}.", env.getFrameworkConfiguration().getJobStateQueueSize());
return;
}
Optional<CloudJobConfiguration> cloudJobConfig = configService.load(jobName);
if (!cloudJobConfig.isPresent() || CloudJobExecutionType.DAEMON != cloudJobConfig.get().getJobExecutionType() || runningService.isJobRunning(jobName)) {
return;
}
regCenter.persist(ReadyNode.getReadyJobNodePath(jobName), "1");
}
/**
* Set misfire disabled.
*
* @param jobName job name
*/
public void setMisfireDisabled(final String jobName) {
Optional<CloudJobConfiguration> cloudJobConfig = configService.load(jobName);
if (cloudJobConfig.isPresent() && null != regCenter.getDirectly(ReadyNode.getReadyJobNodePath(jobName))) {
regCenter.persist(ReadyNode.getReadyJobNodePath(jobName), "1");
}
}
/**
* Get all the eligible job contexts from ready queue.
*
* @param ineligibleJobContexts ineligible job contexts
* @return collection of eligible contexts
*/
public Collection<JobContext> getAllEligibleJobContexts(final Collection<JobContext> ineligibleJobContexts) {
if (!regCenter.isExisted(ReadyNode.ROOT)) {
return Collections.emptyList();
}
Collection<String> ineligibleJobNames = Collections2.transform(ineligibleJobContexts, new Function<JobContext, String>() {
@Override
public String apply(final JobContext input) {
return input.getJobConfig().getJobName();
}
});
List<String> jobNames = regCenter.getChildrenKeys(ReadyNode.ROOT);
List<JobContext> result = new ArrayList<>(jobNames.size());
for (String each : jobNames) {
if (ineligibleJobNames.contains(each)) {
continue;
}
Optional<CloudJobConfiguration> jobConfig = configService.load(each);
if (!jobConfig.isPresent()) {
regCenter.remove(ReadyNode.getReadyJobNodePath(each));
continue;
}
if (!runningService.isJobRunning(each)) {
result.add(JobContext.from(jobConfig.get(), ExecutionType.READY));
}
}
return result;
}
/**
* Remove jobs from ready queue.
*
* @param jobNames collection of jobs to be removed
*/
public void remove(final Collection<String> jobNames) {
for (String each : jobNames) {
String readyJobNode = ReadyNode.getReadyJobNodePath(each);
String timesStr = regCenter.getDirectly(readyJobNode);
int times = null == timesStr ? 0 : Integer.parseInt(timesStr);
if (times <= 1) {
regCenter.remove(readyJobNode);
} else {
regCenter.persist(readyJobNode, Integer.toString(times - 1));
}
}
}
/**
* Get all ready tasks.
*
* @return all ready tasks
*/
public Map<String, Integer> getAllReadyTasks() {
if (!regCenter.isExisted(ReadyNode.ROOT)) {
return Collections.emptyMap();
}
List<String> jobNames = regCenter.getChildrenKeys(ReadyNode.ROOT);
Map<String, Integer> result = new HashMap<>(jobNames.size(), 1);
for (String each : jobNames) {
String times = regCenter.get(ReadyNode.getReadyJobNodePath(each));
if (!Strings.isNullOrEmpty(times)) {
result.put(each, Integer.parseInt(times));
}
}
return result;
}
}
```
|
```package org.apache.shardingsphere.elasticjob.cloud.api;
import org.apache.shardingsphere.elasticjob.cloud.executor.ShardingContexts;
import org.apache.shardingsphere.elasticjob.cloud.fixture.ShardingContextsBuilder;
import org.hamcrest.core.Is;
import org.junit.Assert;
import org.junit.Test;
public final class ShardingContextTest {
@Test
public void assertNew() {
ShardingContexts shardingContexts = ShardingContextsBuilder.getMultipleShardingContexts();
ShardingContext actual = new ShardingContext(shardingContexts, 1);
Assert.assertThat(actual.getJobName(), Is.is(shardingContexts.getJobName()));
Assert.assertThat(actual.getTaskId(), Is.is(shardingContexts.getTaskId()));
Assert.assertThat(actual.getShardingTotalCount(), Is.is(shardingContexts.getShardingTotalCount()));
Assert.assertThat(actual.getJobParameter(), Is.is(shardingContexts.getJobParameter()));
Assert.assertThat(actual.getShardingItem(), Is.is(1));
Assert.assertThat(actual.getShardingParameter(), Is.is(shardingContexts.getShardingItemParameters().get(1)));
}
@Test
public void assertToString() {
Assert.assertThat(new ShardingContext(ShardingContextsBuilder.getMultipleShardingContexts(), 1).toString(),
Is.is("ShardingContext(jobName=test_job, taskId=fake_task_id, shardingTotalCount=2, jobParameter=, shardingItem=1, shardingParameter=B)"));
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.shardingsphere.elasticjob.cloud.api;
import org.apache.shardingsphere.elasticjob.cloud.executor.ShardingContexts;
import lombok.Getter;
import lombok.ToString;
/**
* Sharding context.
*/
@Getter
@ToString
public final class ShardingContext {
/**
* job name.
*/
private final String jobName;
/**
* task ID.
*/
private final String taskId;
/**
* sharding total count.
*/
private final int shardingTotalCount;
/**
* job parameter.
*
* <p>Can configure for same job class, but use different parameter for different job schedule instance.</p>
*
*/
private final String jobParameter;
/**
* Sharding item assigned for this sharding.
*/
private final int shardingItem;
/**
* Sharding parameter assigned for this sharding.
*/
private final String shardingParameter;
public ShardingContext(final ShardingContexts shardingContexts, final int shardingItem) {
jobName = shardingContexts.getJobName();
taskId = shardingContexts.getTaskId();
shardingTotalCount = shardingContexts.getShardingTotalCount();
jobParameter = shardingContexts.getJobParameter();
this.shardingItem = shardingItem;
shardingParameter = shardingContexts.getShardingItemParameters().get(shardingItem);
}
}
```
|
```package org.apache.shardingsphere.elasticjob.cloud.exception;
import org.hamcrest.core.Is;
import org.junit.Assert;
import org.junit.Test;
public final class JobExecutionEnvironmentExceptionTest {
@Test
public void assertGetMessage() {
Assert.assertThat(new JobExecutionEnvironmentException("message is: '%s'", "test").getMessage(), Is.is("message is: 'test'"));
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.shardingsphere.elasticjob.cloud.exception;
/**
* Job execution environment exception.
*/
public final class JobExecutionEnvironmentException extends Exception {
private static final long serialVersionUID = -6670738108926897433L;
public JobExecutionEnvironmentException(final String errorMessage, final Object... args) {
super(String.format(errorMessage, args));
}
}
```
|
```package org.apache.shardingsphere.elasticjob.cloud.fixture.job;
import org.apache.shardingsphere.elasticjob.cloud.api.ShardingContext;
import org.apache.shardingsphere.elasticjob.cloud.api.dataflow.DataflowJob;
import lombok.RequiredArgsConstructor;
import java.util.List;
@RequiredArgsConstructor
public final class TestDataflowJob implements DataflowJob<Object> {
private final JobCaller jobCaller;
@Override
public List<Object> fetchData(final ShardingContext shardingContext) {
return jobCaller.fetchData(shardingContext.getShardingItem());
}
@Override
public void processData(final ShardingContext shardingContext, final List<Object> data) {
for (Object each : data) {
jobCaller.processData(each);
}
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.shardingsphere.elasticjob.cloud.api.dataflow;
import org.apache.shardingsphere.elasticjob.cloud.api.ElasticJob;
import org.apache.shardingsphere.elasticjob.cloud.api.ShardingContext;
import java.util.List;
/**
* Dataflow job.
*
* @param <T> type of data
*/
public interface DataflowJob<T> extends ElasticJob {
/**
* Fetch to be processed data.
*
* @param shardingContext sharding context
* @return to be processed data
*/
List<T> fetchData(ShardingContext shardingContext);
/**
* Process data.
*
* @param shardingContext sharding context
* @param data to be processed data
*/
void processData(ShardingContext shardingContext, List<T> data);
}
```
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.statistics.job;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.statistics.TaskResultMetaData;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.statistics.util.StatisticTimeUtils;
import org.apache.shardingsphere.elasticjob.cloud.statistics.type.task.TaskResultStatistics;
import org.apache.shardingsphere.elasticjob.cloud.statistics.StatisticInterval;
import org.apache.shardingsphere.elasticjob.cloud.statistics.rdb.StatisticRdbRepository;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import com.google.common.base.Optional;
@RunWith(MockitoJUnitRunner.class)
public class TaskResultStatisticJobTest {
private StatisticInterval statisticInterval = StatisticInterval.MINUTE;
private TaskResultMetaData sharedData;
@Mock
private StatisticRdbRepository repository;
private TaskResultStatisticJob taskResultStatisticJob;
@Before
public void setUp() {
taskResultStatisticJob = new TaskResultStatisticJob();
sharedData = new TaskResultMetaData();
taskResultStatisticJob.setStatisticInterval(statisticInterval);
taskResultStatisticJob.setSharedData(sharedData);
taskResultStatisticJob.setRepository(repository);
}
@Test
public void assertBuildJobDetail() {
assertThat(taskResultStatisticJob.buildJobDetail().getKey().getName(), is(TaskResultStatisticJob.class.getSimpleName() + "_" + statisticInterval));
}
@Test
public void assertBuildTrigger() throws SchedulerException {
for (StatisticInterval each : StatisticInterval.values()) {
taskResultStatisticJob.setStatisticInterval(each);
Trigger trigger = taskResultStatisticJob.buildTrigger();
assertThat(trigger.getKey().getName(), is(TaskResultStatisticJob.class.getSimpleName() + "Trigger" + "_" + each));
}
}
@Test
public void assertGetDataMap() throws SchedulerException {
assertThat((StatisticInterval) taskResultStatisticJob.getDataMap().get("statisticInterval"), is(statisticInterval));
assertThat((TaskResultMetaData) taskResultStatisticJob.getDataMap().get("sharedData"), is(sharedData));
assertThat((StatisticRdbRepository) taskResultStatisticJob.getDataMap().get("repository"), is(repository));
}
@Test
public void assertExecuteWhenRepositoryIsEmpty() throws SchedulerException {
Optional<TaskResultStatistics> latestOne = Optional.absent();
for (StatisticInterval each : StatisticInterval.values()) {
taskResultStatisticJob.setStatisticInterval(each);
when(repository.findLatestTaskResultStatistics(each)).thenReturn(latestOne);
when(repository.add(any(TaskResultStatistics.class))).thenReturn(true);
taskResultStatisticJob.execute(null);
verify(repository).findLatestTaskResultStatistics(each);
}
verify(repository, times(3)).add(any(TaskResultStatistics.class));
}
@Test
public void assertExecute() throws SchedulerException {
for (StatisticInterval each : StatisticInterval.values()) {
taskResultStatisticJob.setStatisticInterval(each);
Optional<TaskResultStatistics> latestOne = Optional.of(new TaskResultStatistics(0, 0, each, StatisticTimeUtils.getStatisticTime(each, -3)));
when(repository.findLatestTaskResultStatistics(each)).thenReturn(latestOne);
when(repository.add(any(TaskResultStatistics.class))).thenReturn(true);
taskResultStatisticJob.execute(null);
verify(repository).findLatestTaskResultStatistics(each);
}
verify(repository, times(StatisticInterval.values().length * 3)).add(any(TaskResultStatistics.class));
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.statistics.job;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.statistics.TaskResultMetaData;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.statistics.util.StatisticTimeUtils;
import org.apache.shardingsphere.elasticjob.cloud.statistics.StatisticInterval;
import org.apache.shardingsphere.elasticjob.cloud.statistics.rdb.StatisticRdbRepository;
import org.apache.shardingsphere.elasticjob.cloud.statistics.type.task.TaskResultStatistics;
import com.google.common.base.Optional;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Task result statistic.
*/
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Slf4j
public final class TaskResultStatisticJob extends AbstractStatisticJob {
private StatisticInterval statisticInterval;
private TaskResultMetaData sharedData;
private StatisticRdbRepository repository;
@Override
public JobDetail buildJobDetail() {
JobDetail result = JobBuilder.newJob(this.getClass()).withIdentity(getJobName() + "_" + statisticInterval).build();
result.getJobDataMap().put("statisticUnit", statisticInterval);
return result;
}
@Override
public Trigger buildTrigger() {
return TriggerBuilder.newTrigger()
.withIdentity(getTriggerName() + "_" + statisticInterval)
.withSchedule(CronScheduleBuilder.cronSchedule(statisticInterval.getCron())
.withMisfireHandlingInstructionDoNothing()).build();
}
@Override
public Map<String, Object> getDataMap() {
Map<String, Object> result = new HashMap<>(3);
result.put("statisticInterval", statisticInterval);
result.put("sharedData", sharedData);
result.put("repository", repository);
return result;
}
@Override
public void execute(final JobExecutionContext context) throws JobExecutionException {
Optional<TaskResultStatistics> latestOne = repository.findLatestTaskResultStatistics(statisticInterval);
if (latestOne.isPresent()) {
fillBlankIfNeeded(latestOne.get());
}
TaskResultStatistics taskResultStatistics = new TaskResultStatistics(
sharedData.getSuccessCount(), sharedData.getFailedCount(), statisticInterval,
StatisticTimeUtils.getCurrentStatisticTime(statisticInterval));
log.debug("Add taskResultStatistics, statisticInterval is:{}, successCount is:{}, failedCount is:{}",
statisticInterval, sharedData.getSuccessCount(), sharedData.getFailedCount());
repository.add(taskResultStatistics);
sharedData.reset();
}
private void fillBlankIfNeeded(final TaskResultStatistics latestOne) {
List<Date> blankDateRange = findBlankStatisticTimes(latestOne.getStatisticsTime(), statisticInterval);
if (!blankDateRange.isEmpty()) {
log.debug("Fill blank range of taskResultStatistics, range is:{}", blankDateRange);
}
for (Date each : blankDateRange) {
repository.add(new TaskResultStatistics(latestOne.getSuccessCount(), latestOne.getFailedCount(), statisticInterval, each));
}
}
}
```
|
```package org.apache.shardingsphere.elasticjob.cloud.util.env;
import org.junit.Test;
import static org.junit.Assert.assertNotNull;
public final class IpUtilsTest {
@Test
public void assertGetIp() {
assertNotNull(IpUtils.getIp());
}
@Test
public void assertGetHostName() {
assertNotNull(IpUtils.getHostName());
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.shardingsphere.elasticjob.cloud.util.env;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
/**
* IP address utility.
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class IpUtils {
public static final String IP_REGEX = "((\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3})";
private static volatile String cachedIpAddress;
/**
* Get IP address for localhost.
*
* @return IP address for localhost
*/
public static String getIp() {
if (null != cachedIpAddress) {
return cachedIpAddress;
}
Enumeration<NetworkInterface> netInterfaces;
try {
netInterfaces = NetworkInterface.getNetworkInterfaces();
} catch (final SocketException ex) {
throw new HostException(ex);
}
String localIpAddress = null;
while (netInterfaces.hasMoreElements()) {
NetworkInterface netInterface = netInterfaces.nextElement();
Enumeration<InetAddress> ipAddresses = netInterface.getInetAddresses();
while (ipAddresses.hasMoreElements()) {
InetAddress ipAddress = ipAddresses.nextElement();
if (isPublicIpAddress(ipAddress)) {
String publicIpAddress = ipAddress.getHostAddress();
cachedIpAddress = publicIpAddress;
return publicIpAddress;
}
if (isLocalIpAddress(ipAddress)) {
localIpAddress = ipAddress.getHostAddress();
}
}
}
cachedIpAddress = localIpAddress;
return localIpAddress;
}
private static boolean isPublicIpAddress(final InetAddress ipAddress) {
return !ipAddress.isSiteLocalAddress() && !ipAddress.isLoopbackAddress() && !isV6IpAddress(ipAddress);
}
private static boolean isLocalIpAddress(final InetAddress ipAddress) {
return ipAddress.isSiteLocalAddress() && !ipAddress.isLoopbackAddress() && !isV6IpAddress(ipAddress);
}
private static boolean isV6IpAddress(final InetAddress ipAddress) {
return ipAddress.getHostAddress().contains(":");
}
/**
* Get host name for localhost.
*
* @return host name for localhost
*/
public static String getHostName() {
try {
return InetAddress.getLocalHost().getHostName();
} catch (final UnknownHostException ex) {
return "unknown";
}
}
}
```
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.config.job;
import org.hamcrest.core.Is;
import org.junit.Assert;
import org.junit.Test;
public final class CloudJobConfigurationNodeTest {
@Test
public void assertGetRootNodePath() {
Assert.assertThat(CloudJobConfigurationNode.getRootNodePath("test_job"), Is.is("/config/job/test_job"));
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.config.job;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
/**
* Cloud job configuration node.
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class CloudJobConfigurationNode {
public static final String ROOT = "/config/job";
private static final String JOB_CONFIG = ROOT + "/%s";
static String getRootNodePath(final String jobName) {
return String.format(JOB_CONFIG, jobName);
}
}
```
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.config.app;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.fixture.CloudAppConfigurationBuilder;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.fixture.CloudAppJsonConstants;
import org.apache.shardingsphere.elasticjob.cloud.reg.base.CoordinatorRegistryCenter;
import com.google.common.base.Optional;
import org.hamcrest.core.Is;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.Arrays;
import java.util.Collection;
@RunWith(MockitoJUnitRunner.class)
public final class CloudAppConfigurationServiceTest {
@Mock
private CoordinatorRegistryCenter regCenter;
@InjectMocks
private CloudAppConfigurationService configService;
@Test
public void assertAdd() {
CloudAppConfiguration appConfig = CloudAppConfigurationBuilder.createCloudAppConfiguration("test_app");
configService.add(appConfig);
Mockito.verify(regCenter).persist("/config/app/test_app", CloudAppJsonConstants.getAppJson("test_app"));
}
@Test
public void assertUpdate() {
CloudAppConfiguration appConfig = CloudAppConfigurationBuilder.createCloudAppConfiguration("test_app");
configService.update(appConfig);
Mockito.verify(regCenter).update("/config/app/test_app", CloudAppJsonConstants.getAppJson("test_app"));
}
@Test
public void assertLoadAllWithoutRootNode() {
Mockito.when(regCenter.isExisted("/config/app")).thenReturn(false);
Assert.assertTrue(configService.loadAll().isEmpty());
Mockito.verify(regCenter).isExisted("/config/app");
}
@Test
public void assertLoadAllWithRootNode() {
Mockito.when(regCenter.isExisted("/config/app")).thenReturn(true);
Mockito.when(regCenter.getChildrenKeys(CloudAppConfigurationNode.ROOT)).thenReturn(Arrays.asList("test_app_1", "test_app_2"));
Mockito.when(regCenter.get("/config/app/test_app_1")).thenReturn(CloudAppJsonConstants.getAppJson("test_app_1"));
Collection<CloudAppConfiguration> actual = configService.loadAll();
Assert.assertThat(actual.size(), Is.is(1));
Assert.assertThat(actual.iterator().next().getAppName(), Is.is("test_app_1"));
Mockito.verify(regCenter).isExisted("/config/app");
Mockito.verify(regCenter).getChildrenKeys("/config/app");
Mockito.verify(regCenter).get("/config/app/test_app_1");
Mockito.verify(regCenter).get("/config/app/test_app_2");
}
@Test
public void assertLoadWithoutConfig() {
Optional<CloudAppConfiguration> actual = configService.load("test_app");
Assert.assertFalse(actual.isPresent());
}
@Test
public void assertLoadWithConfig() {
Mockito.when(regCenter.get("/config/app/test_app")).thenReturn(CloudAppJsonConstants.getAppJson("test_app"));
Optional<CloudAppConfiguration> actual = configService.load("test_app");
Assert.assertTrue(actual.isPresent());
Assert.assertThat(actual.get().getAppName(), Is.is("test_app"));
}
@Test
public void assertRemove() {
configService.remove("test_app");
Mockito.verify(regCenter).remove("/config/app/test_app");
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.config.app;
import org.apache.shardingsphere.elasticjob.cloud.reg.base.CoordinatorRegistryCenter;
import com.google.common.base.Optional;
import lombok.RequiredArgsConstructor;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
/**
* Cloud app configuration service.
*/
@RequiredArgsConstructor
public final class CloudAppConfigurationService {
private final CoordinatorRegistryCenter regCenter;
/**
* Add cloud app configuration.
*
* @param appConfig cloud app configuration
*/
public void add(final CloudAppConfiguration appConfig) {
regCenter.persist(CloudAppConfigurationNode.getRootNodePath(appConfig.getAppName()), CloudAppConfigurationGsonFactory.toJson(appConfig));
}
/**
* Update cloud app configuration.
*
* @param appConfig cloud app configuration
*/
public void update(final CloudAppConfiguration appConfig) {
regCenter.update(CloudAppConfigurationNode.getRootNodePath(appConfig.getAppName()), CloudAppConfigurationGsonFactory.toJson(appConfig));
}
/**
* Load app configuration by app name.
*
* @param appName application name
* @return cloud app configuration
*/
public Optional<CloudAppConfiguration> load(final String appName) {
return Optional.fromNullable(CloudAppConfigurationGsonFactory.fromJson(regCenter.get(CloudAppConfigurationNode.getRootNodePath(appName))));
}
/**
* Load all registered cloud app configurations.
*
* @return collection of the registered cloud app configuration
*/
public Collection<CloudAppConfiguration> loadAll() {
if (!regCenter.isExisted(CloudAppConfigurationNode.ROOT)) {
return Collections.emptyList();
}
List<String> appNames = regCenter.getChildrenKeys(CloudAppConfigurationNode.ROOT);
Collection<CloudAppConfiguration> result = new ArrayList<>(appNames.size());
for (String each : appNames) {
Optional<CloudAppConfiguration> config = load(each);
if (config.isPresent()) {
result.add(config.get());
}
}
return result;
}
/**
* Remove cloud app configuration by app name.
*
* @param appName to be removed application name
*/
public void remove(final String appName) {
regCenter.remove(CloudAppConfigurationNode.getRootNodePath(appName));
}
}
```
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.mesos;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.config.app.CloudAppConfigurationService;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.config.job.CloudJobConfiguration;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.config.job.CloudJobConfigurationService;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.config.job.CloudJobExecutionType;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.fixture.CloudJobConfigurationBuilder;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.fixture.TaskNode;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.state.disable.app.DisableAppService;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.state.disable.job.DisableJobService;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.state.running.RunningService;
import org.apache.shardingsphere.elasticjob.cloud.context.ExecutionType;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.config.app.CloudAppConfiguration;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.context.JobContext;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.fixture.CloudAppConfigurationBuilder;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.state.failover.FailoverService;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.state.ready.ReadyService;
import org.apache.shardingsphere.elasticjob.cloud.context.TaskContext;
import org.apache.shardingsphere.elasticjob.cloud.reg.base.CoordinatorRegistryCenter;
import com.google.common.base.Optional;
import com.google.common.collect.Sets;
import org.hamcrest.core.Is;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.unitils.util.ReflectionUtils;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import org.junit.Assert;
import org.mockito.Mockito;
@RunWith(MockitoJUnitRunner.class)
public final class FacadeServiceTest {
@Mock
private CoordinatorRegistryCenter regCenter;
@Mock
private CloudAppConfigurationService appConfigService;
@Mock
private CloudJobConfigurationService jobConfigService;
@Mock
private ReadyService readyService;
@Mock
private RunningService runningService;
@Mock
private FailoverService failoverService;
@Mock
private DisableAppService disableAppService;
@Mock
private DisableJobService disableJobService;
@Mock
private MesosStateService mesosStateService;
private FacadeService facadeService;
@Before
public void setUp() throws NoSuchFieldException {
facadeService = new FacadeService(regCenter);
ReflectionUtils.setFieldValue(facadeService, "jobConfigService", jobConfigService);
ReflectionUtils.setFieldValue(facadeService, "appConfigService", appConfigService);
ReflectionUtils.setFieldValue(facadeService, "readyService", readyService);
ReflectionUtils.setFieldValue(facadeService, "runningService", runningService);
ReflectionUtils.setFieldValue(facadeService, "failoverService", failoverService);
ReflectionUtils.setFieldValue(facadeService, "disableAppService", disableAppService);
ReflectionUtils.setFieldValue(facadeService, "disableJobService", disableJobService);
ReflectionUtils.setFieldValue(facadeService, "mesosStateService", mesosStateService);
}
@Test
public void assertStart() {
facadeService.start();
Mockito.verify(runningService).start();
}
@Test
public void assertGetEligibleJobContext() {
Collection<JobContext> failoverJobContexts = Collections.singletonList(JobContext.from(CloudJobConfigurationBuilder.createCloudJobConfiguration("failover_job"), ExecutionType.FAILOVER));
Collection<JobContext> readyJobContexts = Collections.singletonList(JobContext.from(CloudJobConfigurationBuilder.createCloudJobConfiguration("ready_job"), ExecutionType.READY));
Mockito.when(failoverService.getAllEligibleJobContexts()).thenReturn(failoverJobContexts);
Mockito.when(readyService.getAllEligibleJobContexts(failoverJobContexts)).thenReturn(readyJobContexts);
Collection<JobContext> actual = facadeService.getEligibleJobContext();
Assert.assertThat(actual.size(), Is.is(2));
int i = 0;
for (JobContext each : actual) {
switch (i) {
case 0:
Assert.assertThat(each.getJobConfig().getJobName(), Is.is("failover_job"));
break;
case 1:
Assert.assertThat(each.getJobConfig().getJobName(), Is.is("ready_job"));
break;
default:
break;
}
i++;
}
}
@Test
public void assertRemoveLaunchTasksFromQueue() {
facadeService.removeLaunchTasksFromQueue(Arrays.asList(
TaskContext.from(TaskNode.builder().type(ExecutionType.FAILOVER).build().getTaskNodeValue()),
TaskContext.from(TaskNode.builder().build().getTaskNodeValue())));
Mockito.verify(failoverService).remove(Collections.singletonList(TaskContext.MetaInfo.from(TaskNode.builder().build().getTaskNodePath())));
Mockito.verify(readyService).remove(Sets.newHashSet("test_job"));
}
@Test
public void assertAddRunning() {
TaskContext taskContext = TaskContext.from(TaskNode.builder().build().getTaskNodeValue());
facadeService.addRunning(taskContext);
Mockito.verify(runningService).add(taskContext);
}
@Test
public void assertUpdateDaemonStatus() {
TaskContext taskContext = TaskContext.from(TaskNode.builder().build().getTaskNodeValue());
facadeService.updateDaemonStatus(taskContext, true);
Mockito.verify(runningService).updateIdle(taskContext, true);
}
@Test
public void assertRemoveRunning() {
String taskNodeValue = TaskNode.builder().build().getTaskNodeValue();
TaskContext taskContext = TaskContext.from(taskNodeValue);
facadeService.removeRunning(taskContext);
Mockito.verify(runningService).remove(taskContext);
}
@Test
public void assertRecordFailoverTaskWhenJobConfigNotExisted() {
TaskNode taskNode = TaskNode.builder().type(ExecutionType.FAILOVER).build();
Mockito.when(jobConfigService.load("test_job")).thenReturn(Optional.<CloudJobConfiguration>absent());
facadeService.recordFailoverTask(TaskContext.from(taskNode.getTaskNodeValue()));
Mockito.verify(failoverService, Mockito.times(0)).add(TaskContext.from(taskNode.getTaskNodeValue()));
}
@Test
public void assertRecordFailoverTaskWhenIsFailoverDisabled() {
TaskNode taskNode = TaskNode.builder().type(ExecutionType.FAILOVER).build();
Mockito.when(jobConfigService.load("test_job")).thenReturn(Optional.of(CloudJobConfigurationBuilder.createOtherCloudJobConfiguration("test_job")));
facadeService.recordFailoverTask(TaskContext.from(taskNode.getTaskNodeValue()));
Mockito.verify(failoverService, Mockito.times(0)).add(TaskContext.from(taskNode.getTaskNodeValue()));
}
@Test
public void assertRecordFailoverTaskWhenIsFailoverDisabledAndIsDaemonJob() {
TaskNode taskNode = TaskNode.builder().type(ExecutionType.FAILOVER).build();
Mockito.when(jobConfigService.load("test_job")).thenReturn(Optional.of(CloudJobConfigurationBuilder.createCloudJobConfiguration("test_job", CloudJobExecutionType.DAEMON)));
facadeService.recordFailoverTask(TaskContext.from(taskNode.getTaskNodeValue()));
Mockito.verify(failoverService).add(TaskContext.from(taskNode.getTaskNodeValue()));
}
@Test
public void assertRecordFailoverTaskWhenIsFailoverEnabled() {
TaskNode taskNode = TaskNode.builder().type(ExecutionType.FAILOVER).build();
Mockito.when(jobConfigService.load("test_job")).thenReturn(Optional.of(CloudJobConfigurationBuilder.createCloudJobConfiguration("test_job")));
TaskContext taskContext = TaskContext.from(taskNode.getTaskNodeValue());
facadeService.recordFailoverTask(taskContext);
Mockito.verify(failoverService).add(taskContext);
}
@Test
public void assertLoadAppConfig() {
Optional<CloudAppConfiguration> appConfigOptional = Optional.of(CloudAppConfigurationBuilder.createCloudAppConfiguration("test_app"));
Mockito.when(appConfigService.load("test_app")).thenReturn(appConfigOptional);
Assert.assertThat(facadeService.loadAppConfig("test_app"), Is.is(appConfigOptional));
}
@Test
public void assertLoadJobConfig() {
Optional<CloudJobConfiguration> jobConfigOptional = Optional.of(CloudJobConfigurationBuilder.createCloudJobConfiguration("test_job"));
Mockito.when(jobConfigService.load("test_job")).thenReturn(jobConfigOptional);
Assert.assertThat(facadeService.load("test_job"), Is.is(jobConfigOptional));
}
@Test
public void assertLoadAppConfigWhenAbsent() {
Mockito.when(appConfigService.load("test_app")).thenReturn(Optional.<CloudAppConfiguration>absent());
Assert.assertThat(facadeService.loadAppConfig("test_app"), Is.is(Optional.<CloudAppConfiguration>absent()));
}
@Test
public void assertLoadJobConfigWhenAbsent() {
Mockito.when(jobConfigService.load("test_job")).thenReturn(Optional.<CloudJobConfiguration>absent());
Assert.assertThat(facadeService.load("test_job"), Is.is(Optional.<CloudJobConfiguration>absent()));
}
@Test
public void assertAddDaemonJobToReadyQueue() {
Mockito.when(jobConfigService.load("test_job")).thenReturn(Optional.of(CloudJobConfigurationBuilder.createCloudJobConfiguration("test_job")));
facadeService.addDaemonJobToReadyQueue("test_job");
Mockito.verify(readyService).addDaemon("test_job");
}
@Test
public void assertIsRunningForReadyJobAndNotRunning() {
Mockito.when(runningService.getRunningTasks("test_job")).thenReturn(Collections.<TaskContext>emptyList());
Assert.assertFalse(facadeService.isRunning(TaskContext.from(TaskNode.builder().type(ExecutionType.READY).build().getTaskNodeValue())));
}
@Test
public void assertIsRunningForFailoverJobAndNotRunning() {
Mockito.when(runningService.isTaskRunning(TaskContext.from(TaskNode.builder().type(ExecutionType.FAILOVER).build().getTaskNodeValue()).getMetaInfo())).thenReturn(false);
Assert.assertFalse(facadeService.isRunning(TaskContext.from(TaskNode.builder().type(ExecutionType.FAILOVER).build().getTaskNodeValue())));
}
@Test
public void assertIsRunningForFailoverJobAndRunning() {
Mockito.when(runningService.isTaskRunning(TaskContext.from(TaskNode.builder().type(ExecutionType.FAILOVER).build().getTaskNodeValue()).getMetaInfo())).thenReturn(true);
Assert.assertTrue(facadeService.isRunning(TaskContext.from(TaskNode.builder().type(ExecutionType.FAILOVER).build().getTaskNodeValue())));
}
@Test
public void assertAddMapping() {
facadeService.addMapping("taskId", "localhost");
Mockito.verify(runningService).addMapping("taskId", "localhost");
}
@Test
public void assertPopMapping() {
facadeService.popMapping("taskId");
Mockito.verify(runningService).popMapping("taskId");
}
@Test
public void assertStop() {
facadeService.stop();
Mockito.verify(runningService).clear();
}
@Test
public void assertGetFailoverTaskId() {
TaskNode taskNode = TaskNode.builder().type(ExecutionType.FAILOVER).build();
Mockito.when(jobConfigService.load("test_job")).thenReturn(Optional.of(CloudJobConfigurationBuilder.createCloudJobConfiguration("test_job")));
TaskContext taskContext = TaskContext.from(taskNode.getTaskNodeValue());
facadeService.recordFailoverTask(taskContext);
Mockito.verify(failoverService).add(taskContext);
facadeService.getFailoverTaskId(taskContext.getMetaInfo());
Mockito.verify(failoverService).getTaskId(taskContext.getMetaInfo());
}
@Test
public void assertJobDisabledWhenAppEnabled() {
Mockito.when(jobConfigService.load("test_job")).thenReturn(Optional.of(CloudJobConfigurationBuilder.createCloudJobConfiguration("test_job")));
Mockito.when(disableAppService.isDisabled("test_app")).thenReturn(false);
Mockito.when(disableJobService.isDisabled("test_job")).thenReturn(true);
Assert.assertTrue(facadeService.isJobDisabled("test_job"));
}
@Test
public void assertIsJobEnabled() {
Mockito.when(jobConfigService.load("test_job")).thenReturn(Optional.of(CloudJobConfigurationBuilder.createCloudJobConfiguration("test_job")));
Assert.assertFalse(facadeService.isJobDisabled("test_job"));
}
@Test
public void assertIsJobDisabledWhenAppDisabled() {
Mockito.when(jobConfigService.load("test_job")).thenReturn(Optional.of(CloudJobConfigurationBuilder.createCloudJobConfiguration("test_job")));
Mockito.when(disableAppService.isDisabled("test_app")).thenReturn(true);
Assert.assertTrue(facadeService.isJobDisabled("test_job"));
}
@Test
public void assertIsJobDisabledWhenAppEnabled() {
Mockito.when(jobConfigService.load("test_job")).thenReturn(Optional.of(CloudJobConfigurationBuilder.createCloudJobConfiguration("test_job")));
Mockito.when(disableAppService.isDisabled("test_app")).thenReturn(false);
Mockito.when(disableJobService.isDisabled("test_job")).thenReturn(true);
Assert.assertTrue(facadeService.isJobDisabled("test_job"));
}
@Test
public void assertEnableJob() {
facadeService.enableJob("test_job");
Mockito.verify(disableJobService).remove("test_job");
}
@Test
public void assertDisableJob() {
facadeService.disableJob("test_job");
Mockito.verify(disableJobService).add("test_job");
}
@Test
public void assertLoadExecutor() throws Exception {
facadeService.loadExecutorInfo();
Mockito.verify(mesosStateService).executors();
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.mesos;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.config.app.CloudAppConfigurationService;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.config.job.CloudJobConfiguration;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.state.disable.app.DisableAppService;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.state.disable.job.DisableJobService;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.state.running.RunningService;
import org.apache.shardingsphere.elasticjob.cloud.context.ExecutionType;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.config.app.CloudAppConfiguration;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.config.job.CloudJobConfigurationService;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.config.job.CloudJobExecutionType;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.context.JobContext;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.state.failover.FailoverService;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.state.failover.FailoverTaskInfo;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.state.ready.ReadyService;
import org.apache.shardingsphere.elasticjob.cloud.context.TaskContext;
import org.apache.shardingsphere.elasticjob.cloud.reg.base.CoordinatorRegistryCenter;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.codehaus.jettison.json.JSONException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Mesos facade service.
*/
@Slf4j
public final class FacadeService {
private final CloudAppConfigurationService appConfigService;
private final CloudJobConfigurationService jobConfigService;
private final ReadyService readyService;
private final RunningService runningService;
private final FailoverService failoverService;
private final DisableAppService disableAppService;
private final DisableJobService disableJobService;
private final MesosStateService mesosStateService;
public FacadeService(final CoordinatorRegistryCenter regCenter) {
appConfigService = new CloudAppConfigurationService(regCenter);
jobConfigService = new CloudJobConfigurationService(regCenter);
readyService = new ReadyService(regCenter);
runningService = new RunningService(regCenter);
failoverService = new FailoverService(regCenter);
disableAppService = new DisableAppService(regCenter);
disableJobService = new DisableJobService(regCenter);
mesosStateService = new MesosStateService(regCenter);
}
/**
* Start facade service.
*/
public void start() {
log.info("Elastic Job: Start facade service");
runningService.start();
}
/**
* Get eligible job.
*
* @return collection of eligible job context
*/
public Collection<JobContext> getEligibleJobContext() {
Collection<JobContext> failoverJobContexts = failoverService.getAllEligibleJobContexts();
Collection<JobContext> readyJobContexts = readyService.getAllEligibleJobContexts(failoverJobContexts);
Collection<JobContext> result = new ArrayList<>(failoverJobContexts.size() + readyJobContexts.size());
result.addAll(failoverJobContexts);
result.addAll(readyJobContexts);
return result;
}
/**
* Remove launched task from queue.
*
* @param taskContexts task running contexts
*/
public void removeLaunchTasksFromQueue(final List<TaskContext> taskContexts) {
List<TaskContext> failoverTaskContexts = new ArrayList<>(taskContexts.size());
Collection<String> readyJobNames = new HashSet<>(taskContexts.size(), 1);
for (TaskContext each : taskContexts) {
switch (each.getType()) {
case FAILOVER:
failoverTaskContexts.add(each);
break;
case READY:
readyJobNames.add(each.getMetaInfo().getJobName());
break;
default:
break;
}
}
failoverService.remove(Lists.transform(failoverTaskContexts, new Function<TaskContext, TaskContext.MetaInfo>() {
@Override
public TaskContext.MetaInfo apply(final TaskContext input) {
return input.getMetaInfo();
}
}));
readyService.remove(readyJobNames);
}
/**
* Add task to running queue.
*
* @param taskContext task running context
*/
public void addRunning(final TaskContext taskContext) {
runningService.add(taskContext);
}
/**
* Update daemon task status.
*
* @param taskContext task running context
* @param isIdle set to idle or not
*/
public void updateDaemonStatus(final TaskContext taskContext, final boolean isIdle) {
runningService.updateIdle(taskContext, isIdle);
}
/**
* Remove task from running queue.
*
* @param taskContext task running context
*/
public void removeRunning(final TaskContext taskContext) {
runningService.remove(taskContext);
}
/**
* Record task to failover queue.
*
* @param taskContext task running context
*/
public void recordFailoverTask(final TaskContext taskContext) {
Optional<CloudJobConfiguration> jobConfigOptional = jobConfigService.load(taskContext.getMetaInfo().getJobName());
if (!jobConfigOptional.isPresent()) {
return;
}
if (isDisable(jobConfigOptional.get())) {
return;
}
CloudJobConfiguration jobConfig = jobConfigOptional.get();
if (jobConfig.getTypeConfig().getCoreConfig().isFailover() || CloudJobExecutionType.DAEMON == jobConfig.getJobExecutionType()) {
failoverService.add(taskContext);
}
}
private boolean isDisable(final CloudJobConfiguration jobConfiguration) {
return disableAppService.isDisabled(jobConfiguration.getAppName()) || disableJobService.isDisabled(jobConfiguration.getJobName());
}
/**
* Add transient job to ready queue.
*
* @param jobName job name
*/
public void addTransient(final String jobName) {
readyService.addTransient(jobName);
}
/**
* Load cloud job config.
*
* @param jobName job name
* @return cloud job config
*/
public Optional<CloudJobConfiguration> load(final String jobName) {
return jobConfigService.load(jobName);
}
/**
* Load app config by app name.
*
* @param appName app name
* @return cloud app config
*/
public Optional<CloudAppConfiguration> loadAppConfig(final String appName) {
return appConfigService.load(appName);
}
/**
* Get failover task id by task meta info.
*
* @param metaInfo task meta info
* @return failover task id
*/
public Optional<String> getFailoverTaskId(final TaskContext.MetaInfo metaInfo) {
return failoverService.getTaskId(metaInfo);
}
/**
* Add daemon job to ready queue.
*
* @param jobName job name
*/
public void addDaemonJobToReadyQueue(final String jobName) {
Optional<CloudJobConfiguration> jobConfigOptional = jobConfigService.load(jobName);
if (!jobConfigOptional.isPresent()) {
return;
}
if (isDisable(jobConfigOptional.get())) {
return;
}
readyService.addDaemon(jobName);
}
/**
* Determine whether the task is running or not.
*
* @param taskContext task running context
* @return true is running, otherwise not
*/
public boolean isRunning(final TaskContext taskContext) {
return ExecutionType.FAILOVER != taskContext.getType() && !runningService.getRunningTasks(taskContext.getMetaInfo().getJobName()).isEmpty()
|| ExecutionType.FAILOVER == taskContext.getType() && runningService.isTaskRunning(taskContext.getMetaInfo());
}
/**
* Add mapping of the task primary key and host name.
*
* @param taskId task primary key
* @param hostname host name
*/
public void addMapping(final String taskId, final String hostname) {
runningService.addMapping(taskId, hostname);
}
/**
* Retrieve hostname and then remove task.
*
* @param taskId task primary key
* @return hostname of the removed task
*/
public String popMapping(final String taskId) {
return runningService.popMapping(taskId);
}
/**
* Get all ready tasks.
*
* @return ready tasks
*/
public Map<String, Integer> getAllReadyTasks() {
return readyService.getAllReadyTasks();
}
/**
* Get all running tasks.
*
* @return running tasks
*/
public Map<String, Set<TaskContext>> getAllRunningTasks() {
return runningService.getAllRunningTasks();
}
/**
* Get all failover tasks.
*
* @return failover tasks
*/
public Map<String, Collection<FailoverTaskInfo>> getAllFailoverTasks() {
return failoverService.getAllFailoverTasks();
}
/**
* Determine whether the job is disable or not.
*
* @param jobName job name
* @return true is disabled, otherwise not
*/
public boolean isJobDisabled(final String jobName) {
Optional<CloudJobConfiguration> jobConfiguration = jobConfigService.load(jobName);
return !jobConfiguration.isPresent() || disableAppService.isDisabled(jobConfiguration.get().getAppName()) || disableJobService.isDisabled(jobName);
}
/**
* Enable job.
*
* @param jobName job name
*/
public void enableJob(final String jobName) {
disableJobService.remove(jobName);
}
/**
* Disable job.
*
* @param jobName job name
*/
public void disableJob(final String jobName) {
disableJobService.add(jobName);
}
/**
* Get all running executor info.
*
* @return collection of executor info
* @throws JSONException json exception
*/
public Collection<MesosStateService.ExecutorStateInfo> loadExecutorInfo() throws JSONException {
return mesosStateService.executors();
}
/**
* Stop facade service.
*/
public void stop() {
log.info("Elastic Job: Stop facade service");
// TODO stop scheduler
runningService.clear();
}
}
```
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.statistics;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.config.job.CloudJobConfigurationService;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.config.job.CloudJobExecutionType;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.fixture.CloudJobConfigurationBuilder;
import org.apache.shardingsphere.elasticjob.cloud.event.rdb.JobEventRdbConfiguration;
import org.apache.shardingsphere.elasticjob.cloud.reg.base.CoordinatorRegistryCenter;
import org.apache.shardingsphere.elasticjob.cloud.statistics.StatisticInterval;
import org.apache.shardingsphere.elasticjob.cloud.statistics.rdb.StatisticRdbRepository;
import org.apache.shardingsphere.elasticjob.cloud.statistics.type.job.JobRegisterStatistics;
import org.apache.shardingsphere.elasticjob.cloud.statistics.type.job.JobRunningStatistics;
import org.apache.shardingsphere.elasticjob.cloud.statistics.type.task.TaskResultStatistics;
import org.apache.shardingsphere.elasticjob.cloud.statistics.type.task.TaskRunningStatistics;
import com.google.common.base.Optional;
import com.google.common.collect.Lists;
import org.hamcrest.core.Is;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.unitils.util.ReflectionUtils;
import java.util.Date;
@RunWith(MockitoJUnitRunner.class)
public class StatisticManagerTest {
@Mock
private CoordinatorRegistryCenter regCenter;
@Mock
private Optional<JobEventRdbConfiguration> jobEventRdbConfiguration;
@Mock
private StatisticRdbRepository rdbRepository;
@Mock
private StatisticsScheduler scheduler;
@Mock
private CloudJobConfigurationService configurationService;
private StatisticManager statisticManager;
@Before
public void setUp() {
statisticManager = StatisticManager.getInstance(regCenter, jobEventRdbConfiguration);
}
@After
public void tearDown() throws NoSuchFieldException {
statisticManager.shutdown();
ReflectionUtils.setFieldValue(StatisticManager.class, StatisticManager.class.getDeclaredField("instance"), null);
Mockito.reset(configurationService);
Mockito.reset(rdbRepository);
}
@Test
public void assertGetInstance() {
Assert.assertThat(statisticManager, Is.is(StatisticManager.getInstance(regCenter, jobEventRdbConfiguration)));
}
@Test
public void assertStartupWhenRdbIsNotConfigured() throws NoSuchFieldException {
ReflectionUtils.setFieldValue(statisticManager, "rdbRepository", null);
statisticManager.startup();
}
@Test
public void assertStartupWhenRdbIsConfigured() throws NoSuchFieldException {
ReflectionUtils.setFieldValue(statisticManager, "rdbRepository", rdbRepository);
statisticManager.startup();
}
@Test
public void assertShutdown() throws NoSuchFieldException {
ReflectionUtils.setFieldValue(statisticManager, "scheduler", scheduler);
statisticManager.shutdown();
Mockito.verify(scheduler).shutdown();
}
@Test
public void assertTaskRun() throws NoSuchFieldException {
statisticManager.taskRunSuccessfully();
statisticManager.taskRunFailed();
}
@Test
public void assertTaskResultStatisticsWhenRdbIsNotConfigured() throws NoSuchFieldException {
ReflectionUtils.setFieldValue(statisticManager, "rdbRepository", null);
Assert.assertThat(statisticManager.getTaskResultStatisticsWeekly().getSuccessCount(), Is.is(0));
Assert.assertThat(statisticManager.getTaskResultStatisticsWeekly().getFailedCount(), Is.is(0));
Assert.assertThat(statisticManager.getTaskResultStatisticsSinceOnline().getSuccessCount(), Is.is(0));
Assert.assertThat(statisticManager.getTaskResultStatisticsSinceOnline().getFailedCount(), Is.is(0));
}
@Test
public void assertTaskResultStatisticsWhenRdbIsConfigured() throws NoSuchFieldException {
ReflectionUtils.setFieldValue(statisticManager, "rdbRepository", rdbRepository);
Mockito.when(rdbRepository.getSummedTaskResultStatistics(Mockito.any(Date.class), Mockito.any(StatisticInterval.class)))
.thenReturn(new TaskResultStatistics(10, 10, StatisticInterval.DAY, new Date()));
Assert.assertThat(statisticManager.getTaskResultStatisticsWeekly().getSuccessCount(), Is.is(10));
Assert.assertThat(statisticManager.getTaskResultStatisticsWeekly().getFailedCount(), Is.is(10));
Assert.assertThat(statisticManager.getTaskResultStatisticsSinceOnline().getSuccessCount(), Is.is(10));
Assert.assertThat(statisticManager.getTaskResultStatisticsSinceOnline().getFailedCount(), Is.is(10));
Mockito.verify(rdbRepository, Mockito.times(4)).getSummedTaskResultStatistics(Mockito.any(Date.class), Mockito.any(StatisticInterval.class));
}
@Test
public void assertJobTypeStatistics() throws NoSuchFieldException {
ReflectionUtils.setFieldValue(statisticManager, "configurationService", configurationService);
Mockito.when(configurationService.loadAll()).thenReturn(Lists.newArrayList(
CloudJobConfigurationBuilder.createCloudJobConfiguration("test_job_simple"),
CloudJobConfigurationBuilder.createDataflowCloudJobConfiguration("test_job_dataflow"),
CloudJobConfigurationBuilder.createScriptCloudJobConfiguration("test_job_script")));
Assert.assertThat(statisticManager.getJobTypeStatistics().getSimpleJobCount(), Is.is(1));
Assert.assertThat(statisticManager.getJobTypeStatistics().getDataflowJobCount(), Is.is(1));
Assert.assertThat(statisticManager.getJobTypeStatistics().getScriptJobCount(), Is.is(1));
Mockito.verify(configurationService, Mockito.times(3)).loadAll();
}
@Test
public void assertJobExecutionTypeStatistics() throws NoSuchFieldException {
ReflectionUtils.setFieldValue(statisticManager, "configurationService", configurationService);
Mockito.when(configurationService.loadAll()).thenReturn(Lists.newArrayList(
CloudJobConfigurationBuilder.createCloudJobConfiguration("test_job_1", CloudJobExecutionType.DAEMON),
CloudJobConfigurationBuilder.createCloudJobConfiguration("test_job_2", CloudJobExecutionType.TRANSIENT)));
Assert.assertThat(statisticManager.getJobExecutionTypeStatistics().getDaemonJobCount(), Is.is(1));
Assert.assertThat(statisticManager.getJobExecutionTypeStatistics().getTransientJobCount(), Is.is(1));
Mockito.verify(configurationService, Mockito.times(2)).loadAll();
}
@Test
public void assertFindTaskRunningStatisticsWhenRdbIsNotConfigured() throws NoSuchFieldException {
ReflectionUtils.setFieldValue(statisticManager, "rdbRepository", null);
Assert.assertTrue(statisticManager.findTaskRunningStatisticsWeekly().isEmpty());
}
@Test
public void assertFindTaskRunningStatisticsWhenRdbIsConfigured() throws NoSuchFieldException {
ReflectionUtils.setFieldValue(statisticManager, "rdbRepository", rdbRepository);
Mockito.when(rdbRepository.findTaskRunningStatistics(Mockito.any(Date.class)))
.thenReturn(Lists.newArrayList(new TaskRunningStatistics(10, new Date())));
Assert.assertThat(statisticManager.findTaskRunningStatisticsWeekly().size(), Is.is(1));
Mockito.verify(rdbRepository).findTaskRunningStatistics(Mockito.any(Date.class));
}
@Test
public void assertFindJobRunningStatisticsWhenRdbIsNotConfigured() throws NoSuchFieldException {
ReflectionUtils.setFieldValue(statisticManager, "rdbRepository", null);
Assert.assertTrue(statisticManager.findJobRunningStatisticsWeekly().isEmpty());
}
@Test
public void assertFindJobRunningStatisticsWhenRdbIsConfigured() throws NoSuchFieldException {
ReflectionUtils.setFieldValue(statisticManager, "rdbRepository", rdbRepository);
Mockito.when(rdbRepository.findJobRunningStatistics(Mockito.any(Date.class)))
.thenReturn(Lists.newArrayList(new JobRunningStatistics(10, new Date())));
Assert.assertThat(statisticManager.findJobRunningStatisticsWeekly().size(), Is.is(1));
Mockito.verify(rdbRepository).findJobRunningStatistics(Mockito.any(Date.class));
}
@Test
public void assertFindJobRegisterStatisticsWhenRdbIsNotConfigured() throws NoSuchFieldException {
ReflectionUtils.setFieldValue(statisticManager, "rdbRepository", null);
Assert.assertTrue(statisticManager.findJobRegisterStatisticsSinceOnline().isEmpty());
}
@Test
public void assertFindJobRegisterStatisticsWhenRdbIsConfigured() throws NoSuchFieldException {
ReflectionUtils.setFieldValue(statisticManager, "rdbRepository", rdbRepository);
Mockito.when(rdbRepository.findJobRegisterStatistics(Mockito.any(Date.class)))
.thenReturn(Lists.newArrayList(new JobRegisterStatistics(10, new Date())));
Assert.assertThat(statisticManager.findJobRegisterStatisticsSinceOnline().size(), Is.is(1));
Mockito.verify(rdbRepository).findJobRegisterStatistics(Mockito.any(Date.class));
}
@Test
public void assertFindLatestTaskResultStatisticsWhenRdbIsNotConfigured() throws NoSuchFieldException {
ReflectionUtils.setFieldValue(statisticManager, "rdbRepository", null);
for (StatisticInterval each : StatisticInterval.values()) {
TaskResultStatistics actual = statisticManager.findLatestTaskResultStatistics(each);
Assert.assertThat(actual.getSuccessCount(), Is.is(0));
Assert.assertThat(actual.getFailedCount(), Is.is(0));
}
}
@Test
public void assertFindLatestTaskResultStatisticsWhenRdbIsConfigured() throws NoSuchFieldException {
ReflectionUtils.setFieldValue(statisticManager, "rdbRepository", rdbRepository);
for (StatisticInterval each : StatisticInterval.values()) {
Mockito.when(rdbRepository.findLatestTaskResultStatistics(each))
.thenReturn(Optional.of(new TaskResultStatistics(10, 5, each, new Date())));
TaskResultStatistics actual = statisticManager.findLatestTaskResultStatistics(each);
Assert.assertThat(actual.getSuccessCount(), Is.is(10));
Assert.assertThat(actual.getFailedCount(), Is.is(5));
}
Mockito.verify(rdbRepository, Mockito.times(StatisticInterval.values().length)).findLatestTaskResultStatistics(Mockito.any(StatisticInterval.class));
}
@Test
public void assertFindTaskResultStatisticsDailyWhenRdbIsNotConfigured() throws NoSuchFieldException {
ReflectionUtils.setFieldValue(statisticManager, "rdbRepository", null);
Assert.assertTrue(statisticManager.findTaskResultStatisticsDaily().isEmpty());
}
@Test
public void assertFindTaskResultStatisticsDailyWhenRdbIsConfigured() throws NoSuchFieldException {
ReflectionUtils.setFieldValue(statisticManager, "rdbRepository", rdbRepository);
Mockito.when(rdbRepository.findTaskResultStatistics(Mockito.any(Date.class), Mockito.any(StatisticInterval.class)))
.thenReturn(Lists.newArrayList(new TaskResultStatistics(10, 5, StatisticInterval.MINUTE, new Date())));
Assert.assertThat(statisticManager.findTaskResultStatisticsDaily().size(), Is.is(1));
Mockito.verify(rdbRepository).findTaskResultStatistics(Mockito.any(Date.class), Mockito.any(StatisticInterval.class));
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.statistics;
import org.apache.shardingsphere.elasticjob.cloud.api.JobType;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.statistics.job.JobRunningStatisticJob;
import org.apache.shardingsphere.elasticjob.cloud.event.rdb.JobEventRdbConfiguration;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.config.job.CloudJobConfiguration;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.config.job.CloudJobConfigurationService;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.config.job.CloudJobExecutionType;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.statistics.job.RegisteredJobStatisticJob;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.statistics.job.TaskResultStatisticJob;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.statistics.util.StatisticTimeUtils;
import org.apache.shardingsphere.elasticjob.cloud.statistics.type.job.JobRegisterStatistics;
import org.apache.shardingsphere.elasticjob.cloud.statistics.type.task.TaskResultStatistics;
import org.apache.shardingsphere.elasticjob.cloud.reg.base.CoordinatorRegistryCenter;
import org.apache.shardingsphere.elasticjob.cloud.statistics.StatisticInterval;
import org.apache.shardingsphere.elasticjob.cloud.statistics.rdb.StatisticRdbRepository;
import org.apache.shardingsphere.elasticjob.cloud.statistics.type.job.JobExecutionTypeStatistics;
import org.apache.shardingsphere.elasticjob.cloud.statistics.type.job.JobRunningStatistics;
import org.apache.shardingsphere.elasticjob.cloud.statistics.type.job.JobTypeStatistics;
import org.apache.shardingsphere.elasticjob.cloud.statistics.type.task.TaskRunningStatistics;
import com.google.common.base.Optional;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Statistic manager.
*/
@Slf4j
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
public final class StatisticManager {
private static volatile StatisticManager instance;
private final CoordinatorRegistryCenter registryCenter;
private final CloudJobConfigurationService configurationService;
private final Optional<JobEventRdbConfiguration> jobEventRdbConfiguration;
private final StatisticsScheduler scheduler;
private final Map<StatisticInterval, TaskResultMetaData> statisticData;
private StatisticRdbRepository rdbRepository;
private StatisticManager(final CoordinatorRegistryCenter registryCenter, final Optional<JobEventRdbConfiguration> jobEventRdbConfiguration,
final StatisticsScheduler scheduler, final Map<StatisticInterval, TaskResultMetaData> statisticData) {
this.registryCenter = registryCenter;
this.configurationService = new CloudJobConfigurationService(registryCenter);
this.jobEventRdbConfiguration = jobEventRdbConfiguration;
this.scheduler = scheduler;
this.statisticData = statisticData;
}
/**
* Get statistic manager.
*
* @param regCenter registry center
* @param jobEventRdbConfiguration rdb configuration
* @return statistic manager
*/
public static StatisticManager getInstance(final CoordinatorRegistryCenter regCenter, final Optional<JobEventRdbConfiguration> jobEventRdbConfiguration) {
if (null == instance) {
synchronized (StatisticManager.class) {
if (null == instance) {
Map<StatisticInterval, TaskResultMetaData> statisticData = new HashMap<>();
statisticData.put(StatisticInterval.MINUTE, new TaskResultMetaData());
statisticData.put(StatisticInterval.HOUR, new TaskResultMetaData());
statisticData.put(StatisticInterval.DAY, new TaskResultMetaData());
instance = new StatisticManager(regCenter, jobEventRdbConfiguration, new StatisticsScheduler(), statisticData);
init();
}
}
}
return instance;
}
private static void init() {
if (instance.jobEventRdbConfiguration.isPresent()) {
try {
instance.rdbRepository = new StatisticRdbRepository(instance.jobEventRdbConfiguration.get().getDataSource());
} catch (final SQLException ex) {
log.error("Init StatisticRdbRepository error:", ex);
}
}
}
/**
* Startup.
*/
public void startup() {
if (null != rdbRepository) {
scheduler.start();
scheduler.register(new TaskResultStatisticJob(StatisticInterval.MINUTE, statisticData.get(StatisticInterval.MINUTE), rdbRepository));
scheduler.register(new TaskResultStatisticJob(StatisticInterval.HOUR, statisticData.get(StatisticInterval.HOUR), rdbRepository));
scheduler.register(new TaskResultStatisticJob(StatisticInterval.DAY, statisticData.get(StatisticInterval.DAY), rdbRepository));
scheduler.register(new JobRunningStatisticJob(registryCenter, rdbRepository));
scheduler.register(new RegisteredJobStatisticJob(configurationService, rdbRepository));
}
}
/**
* Shutdown.
*/
public void shutdown() {
scheduler.shutdown();
}
/**
* Run task successfully.
*/
public void taskRunSuccessfully() {
statisticData.get(StatisticInterval.MINUTE).incrementAndGetSuccessCount();
statisticData.get(StatisticInterval.HOUR).incrementAndGetSuccessCount();
statisticData.get(StatisticInterval.DAY).incrementAndGetSuccessCount();
}
/**
* Run task failed.
*/
public void taskRunFailed() {
statisticData.get(StatisticInterval.MINUTE).incrementAndGetFailedCount();
statisticData.get(StatisticInterval.HOUR).incrementAndGetFailedCount();
statisticData.get(StatisticInterval.DAY).incrementAndGetFailedCount();
}
private boolean isRdbConfigured() {
return null != rdbRepository;
}
/**
* Get statistic of the recent week.
* @return task result statistic
*/
public TaskResultStatistics getTaskResultStatisticsWeekly() {
if (!isRdbConfigured()) {
return new TaskResultStatistics(0, 0, StatisticInterval.DAY, new Date());
}
return rdbRepository.getSummedTaskResultStatistics(StatisticTimeUtils.getStatisticTime(StatisticInterval.DAY, -7), StatisticInterval.DAY);
}
/**
* Get statistic since online.
*
* @return task result statistic
*/
public TaskResultStatistics getTaskResultStatisticsSinceOnline() {
if (!isRdbConfigured()) {
return new TaskResultStatistics(0, 0, StatisticInterval.DAY, new Date());
}
return rdbRepository.getSummedTaskResultStatistics(getOnlineDate(), StatisticInterval.DAY);
}
/**
* Get the latest statistic of the specified interval.
* @param statisticInterval statistic interval
* @return task result statistic
*/
public TaskResultStatistics findLatestTaskResultStatistics(final StatisticInterval statisticInterval) {
if (isRdbConfigured()) {
Optional<TaskResultStatistics> result = rdbRepository.findLatestTaskResultStatistics(statisticInterval);
if (result.isPresent()) {
return result.get();
}
}
return new TaskResultStatistics(0, 0, statisticInterval, new Date());
}
/**
* Get statistic of the recent day.
*
* @return task result statistic
*/
public List<TaskResultStatistics> findTaskResultStatisticsDaily() {
if (!isRdbConfigured()) {
return Collections.emptyList();
}
return rdbRepository.findTaskResultStatistics(StatisticTimeUtils.getStatisticTime(StatisticInterval.HOUR, -24), StatisticInterval.MINUTE);
}
/**
* Get job type statistics.
*
* @return job type statistics
*/
public JobTypeStatistics getJobTypeStatistics() {
int scriptJobCnt = 0;
int simpleJobCnt = 0;
int dataflowJobCnt = 0;
for (CloudJobConfiguration each : configurationService.loadAll()) {
if (JobType.SCRIPT.equals(each.getTypeConfig().getJobType())) {
scriptJobCnt++;
} else if (JobType.SIMPLE.equals(each.getTypeConfig().getJobType())) {
simpleJobCnt++;
} else if (JobType.DATAFLOW.equals(each.getTypeConfig().getJobType())) {
dataflowJobCnt++;
}
}
return new JobTypeStatistics(scriptJobCnt, simpleJobCnt, dataflowJobCnt);
}
/**
* Get job execution type statistics.
*
* @return Job execution type statistics data object
*/
public JobExecutionTypeStatistics getJobExecutionTypeStatistics() {
int transientJobCnt = 0;
int daemonJobCnt = 0;
for (CloudJobConfiguration each : configurationService.loadAll()) {
if (CloudJobExecutionType.TRANSIENT.equals(each.getJobExecutionType())) {
transientJobCnt++;
} else if (CloudJobExecutionType.DAEMON.equals(each.getJobExecutionType())) {
daemonJobCnt++;
}
}
return new JobExecutionTypeStatistics(transientJobCnt, daemonJobCnt);
}
/**
* Get the collection of task statistics in the most recent week.
*
* @return Collection of running task statistics data objects
*/
public List<TaskRunningStatistics> findTaskRunningStatisticsWeekly() {
if (!isRdbConfigured()) {
return Collections.emptyList();
}
return rdbRepository.findTaskRunningStatistics(StatisticTimeUtils.getStatisticTime(StatisticInterval.DAY, -7));
}
/**
* Get the collection of job statistics in the most recent week.
*
* @return collection of running task statistics data objects
*/
public List<JobRunningStatistics> findJobRunningStatisticsWeekly() {
if (!isRdbConfigured()) {
return Collections.emptyList();
}
return rdbRepository.findJobRunningStatistics(StatisticTimeUtils.getStatisticTime(StatisticInterval.DAY, -7));
}
/**
* Get running task statistics data collection since online.
*
* @return collection of running task statistics data objects
*/
public List<JobRegisterStatistics> findJobRegisterStatisticsSinceOnline() {
if (!isRdbConfigured()) {
return Collections.emptyList();
}
return rdbRepository.findJobRegisterStatistics(getOnlineDate());
}
private Date getOnlineDate() {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
try {
return formatter.parse("2016-12-16");
} catch (final ParseException ex) {
return null;
}
}
}
```
|
```package org.apache.shardingsphere.elasticjob.cloud.fixture.config;
import org.apache.shardingsphere.elasticjob.cloud.config.JobTypeConfiguration;
import org.apache.shardingsphere.elasticjob.cloud.config.JobRootConfiguration;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
public final class TestJobRootConfiguration implements JobRootConfiguration {
private final JobTypeConfiguration typeConfig;
@Override
public JobTypeConfiguration getTypeConfig() {
return typeConfig;
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.shardingsphere.elasticjob.cloud.config;
/**
* Job root configuration.
*/
public interface JobRootConfiguration {
/**
* Get type Configuration.
*
* @return Job type configuration
*/
JobTypeConfiguration getTypeConfig();
}
```
|
```package org.apache.shardingsphere.elasticjob.cloud.executor;
import org.apache.shardingsphere.elasticjob.cloud.executor.fixture.TestScriptJobConfiguration;
import org.apache.shardingsphere.elasticjob.cloud.context.ExecutionType;
import org.apache.mesos.ExecutorDriver;
import org.apache.mesos.Protos.TaskID;
import org.apache.mesos.Protos.TaskState;
import org.apache.mesos.Protos.TaskStatus;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.quartz.JobExecutionContext;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public final class DaemonTaskSchedulerTest {
@Mock
private JobFacade jobFacade;
@Mock
private ExecutorDriver executorDriver;
@Mock
private JobExecutionContext jobExecutionContext;
@Mock
private AbstractElasticJobExecutor jobExecutor;
@Mock
private ShardingContexts shardingContexts;
private TaskID taskId = TaskID.newBuilder().setValue(String.format("%s@-@0@-@%s@-@fake_slave_id@-@0", "test_job", ExecutionType.READY)).build();
private DaemonTaskScheduler.DaemonJob daemonJob;
@Before
public void setUp() throws NoSuchFieldException {
daemonJob = new DaemonTaskScheduler.DaemonJob();
daemonJob.setElasticJob(null);
daemonJob.setJobFacade(jobFacade);
daemonJob.setExecutorDriver(executorDriver);
daemonJob.setTaskId(taskId);
}
@Test
public void assertJobRun() throws Exception {
when(jobFacade.getShardingContexts()).thenReturn(shardingContexts);
when(jobFacade.loadJobRootConfiguration(true)).thenReturn(new TestScriptJobConfiguration("test.sh"));
daemonJob.execute(jobExecutionContext);
verify(shardingContexts).setAllowSendJobEvent(true);
verify(executorDriver).sendStatusUpdate(TaskStatus.newBuilder().setTaskId(taskId).setState(TaskState.TASK_RUNNING).setMessage("BEGIN").build());
verify(executorDriver).sendStatusUpdate(TaskStatus.newBuilder().setTaskId(taskId).setState(TaskState.TASK_RUNNING).setMessage("COMPLETE").build());
verify(shardingContexts).setCurrentJobEventSamplingCount(0);
}
@Test
public void assertJobRunWithEventSampling() throws Exception {
when(shardingContexts.getJobEventSamplingCount()).thenReturn(2);
when(jobFacade.getShardingContexts()).thenReturn(shardingContexts);
when(jobFacade.loadJobRootConfiguration(true)).thenReturn(new TestScriptJobConfiguration("test.sh"));
daemonJob.execute(jobExecutionContext);
verify(shardingContexts).setCurrentJobEventSamplingCount(1);
verify(shardingContexts).setAllowSendJobEvent(false);
when(shardingContexts.getCurrentJobEventSamplingCount()).thenReturn(1);
daemonJob.execute(jobExecutionContext);
verify(shardingContexts).setAllowSendJobEvent(true);
verify(executorDriver).sendStatusUpdate(TaskStatus.newBuilder().setTaskId(taskId).setState(TaskState.TASK_RUNNING).setMessage("BEGIN").build());
verify(executorDriver).sendStatusUpdate(TaskStatus.newBuilder().setTaskId(taskId).setState(TaskState.TASK_RUNNING).setMessage("COMPLETE").build());
verify(shardingContexts).setCurrentJobEventSamplingCount(0);
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.shardingsphere.elasticjob.cloud.executor;
import org.apache.shardingsphere.elasticjob.cloud.api.ElasticJob;
import org.apache.shardingsphere.elasticjob.cloud.config.JobRootConfiguration;
import org.apache.shardingsphere.elasticjob.cloud.exception.JobSystemException;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import org.apache.mesos.ExecutorDriver;
import org.apache.mesos.Protos;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.plugins.management.ShutdownHookPlugin;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
/**
* Daemon task scheduler.
*/
@RequiredArgsConstructor
public final class DaemonTaskScheduler {
public static final String ELASTIC_JOB_DATA_MAP_KEY = "elasticJob";
private static final String JOB_FACADE_DATA_MAP_KEY = "jobFacade";
private static final String EXECUTOR_DRIVER_DATA_MAP_KEY = "executorDriver";
private static final String TASK_ID_DATA_MAP_KEY = "taskId";
private static final ConcurrentHashMap<String, Scheduler> RUNNING_SCHEDULERS = new ConcurrentHashMap<>(1024, 1);
private final ElasticJob elasticJob;
private final JobRootConfiguration jobRootConfig;
private final JobFacade jobFacade;
private final ExecutorDriver executorDriver;
private final Protos.TaskID taskId;
/**
* Init the job.
*/
public void init() {
JobDetail jobDetail = JobBuilder.newJob(DaemonJob.class).withIdentity(jobRootConfig.getTypeConfig().getCoreConfig().getJobName()).build();
jobDetail.getJobDataMap().put(ELASTIC_JOB_DATA_MAP_KEY, elasticJob);
jobDetail.getJobDataMap().put(JOB_FACADE_DATA_MAP_KEY, jobFacade);
jobDetail.getJobDataMap().put(EXECUTOR_DRIVER_DATA_MAP_KEY, executorDriver);
jobDetail.getJobDataMap().put(TASK_ID_DATA_MAP_KEY, taskId);
try {
scheduleJob(initializeScheduler(), jobDetail, taskId.getValue(), jobRootConfig.getTypeConfig().getCoreConfig().getCron());
} catch (final SchedulerException ex) {
throw new JobSystemException(ex);
}
}
private Scheduler initializeScheduler() throws SchedulerException {
StdSchedulerFactory factory = new StdSchedulerFactory();
factory.initialize(getBaseQuartzProperties());
return factory.getScheduler();
}
private Properties getBaseQuartzProperties() {
Properties result = new Properties();
result.put("org.quartz.threadPool.class", org.quartz.simpl.SimpleThreadPool.class.getName());
result.put("org.quartz.threadPool.threadCount", "1");
result.put("org.quartz.scheduler.instanceName", taskId.getValue());
if (!jobRootConfig.getTypeConfig().getCoreConfig().isMisfire()) {
result.put("org.quartz.jobStore.misfireThreshold", "1");
}
result.put("org.quartz.plugin.shutdownhook.class", ShutdownHookPlugin.class.getName());
result.put("org.quartz.plugin.shutdownhook.cleanShutdown", Boolean.TRUE.toString());
return result;
}
private void scheduleJob(final Scheduler scheduler, final JobDetail jobDetail, final String triggerIdentity, final String cron) {
try {
if (!scheduler.checkExists(jobDetail.getKey())) {
scheduler.scheduleJob(jobDetail, createTrigger(triggerIdentity, cron));
}
scheduler.start();
RUNNING_SCHEDULERS.putIfAbsent(scheduler.getSchedulerName(), scheduler);
} catch (final SchedulerException ex) {
throw new JobSystemException(ex);
}
}
private CronTrigger createTrigger(final String triggerIdentity, final String cron) {
return TriggerBuilder.newTrigger().withIdentity(triggerIdentity).withSchedule(CronScheduleBuilder.cronSchedule(cron).withMisfireHandlingInstructionDoNothing()).build();
}
/**
* Shutdown scheduling the task.
*
* @param taskID task id
*/
public static void shutdown(final Protos.TaskID taskID) {
Scheduler scheduler = RUNNING_SCHEDULERS.remove(taskID.getValue());
if (null != scheduler) {
try {
scheduler.shutdown();
} catch (final SchedulerException ex) {
throw new JobSystemException(ex);
}
}
}
/**
* Daemon job.
*/
public static final class DaemonJob implements Job {
@Setter
private ElasticJob elasticJob;
@Setter
private JobFacade jobFacade;
@Setter
private ExecutorDriver executorDriver;
@Setter
private Protos.TaskID taskId;
@Override
public void execute(final JobExecutionContext context) throws JobExecutionException {
ShardingContexts shardingContexts = jobFacade.getShardingContexts();
int jobEventSamplingCount = shardingContexts.getJobEventSamplingCount();
int currentJobEventSamplingCount = shardingContexts.getCurrentJobEventSamplingCount();
if (jobEventSamplingCount > 0 && ++currentJobEventSamplingCount < jobEventSamplingCount) {
shardingContexts.setCurrentJobEventSamplingCount(currentJobEventSamplingCount);
jobFacade.getShardingContexts().setAllowSendJobEvent(false);
JobExecutorFactory.getJobExecutor(elasticJob, jobFacade).execute();
} else {
jobFacade.getShardingContexts().setAllowSendJobEvent(true);
executorDriver.sendStatusUpdate(Protos.TaskStatus.newBuilder().setTaskId(taskId).setState(Protos.TaskState.TASK_RUNNING).setMessage("BEGIN").build());
JobExecutorFactory.getJobExecutor(elasticJob, jobFacade).execute();
executorDriver.sendStatusUpdate(Protos.TaskStatus.newBuilder().setTaskId(taskId).setState(Protos.TaskState.TASK_RUNNING).setMessage("COMPLETE").build());
shardingContexts.setCurrentJobEventSamplingCount(0);
}
}
}
}
```
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.producer;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
import org.quartz.JobExecutionException;
import org.quartz.JobKey;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
@RunWith(MockitoJUnitRunner.class)
public final class TransientProducerRepositoryTest {
private final JobKey jobKey = JobKey.jobKey("0/45 * * * * ?");
private final String jobName = "test_job";
private TransientProducerRepository transientProducerRepository = new TransientProducerRepository();
@Test
public void assertPutJobKey() throws JobExecutionException {
transientProducerRepository.put(jobKey, jobName);
assertThat(transientProducerRepository.get(jobKey).get(0), is(jobName));
transientProducerRepository.remove(jobName);
}
@Test
public void assertPutJobWithChangedCron() throws JobExecutionException {
transientProducerRepository.put(jobKey, jobName);
JobKey newJobKey = JobKey.jobKey("0/15 * * * * ?");
transientProducerRepository.put(newJobKey, jobName);
assertTrue(transientProducerRepository.get(jobKey).isEmpty());
assertThat(transientProducerRepository.get(newJobKey).get(0), is(jobName));
transientProducerRepository.remove(jobName);
}
@Test
public void assertPutMoreJobWithChangedCron() throws JobExecutionException {
String jobName2 = "other_test_job";
transientProducerRepository.put(jobKey, jobName);
transientProducerRepository.put(jobKey, jobName2);
JobKey newJobKey = JobKey.jobKey("0/15 * * * * ?");
transientProducerRepository.put(newJobKey, jobName);
assertThat(transientProducerRepository.get(jobKey).get(0), is(jobName2));
assertThat(transientProducerRepository.get(newJobKey).get(0), is(jobName));
transientProducerRepository.remove(jobName);
transientProducerRepository.remove(jobName2);
}
@Test
public void assertRemoveJobKey() throws JobExecutionException {
transientProducerRepository.put(jobKey, jobName);
transientProducerRepository.remove(jobName);
assertTrue(transientProducerRepository.get(jobKey).isEmpty());
}
@Test
public void assertContainsKey() {
transientProducerRepository.put(jobKey, jobName);
assertTrue(transientProducerRepository.containsKey(jobKey));
transientProducerRepository.remove(jobName);
assertFalse(transientProducerRepository.containsKey(jobKey));
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.producer;
import org.quartz.JobKey;
import java.util.Collections;
import java.util.List;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* Transient producer repository.
*/
final class TransientProducerRepository {
private final ConcurrentHashMap<JobKey, List<String>> cronTasks = new ConcurrentHashMap<>(256, 1);
synchronized void put(final JobKey jobKey, final String jobName) {
remove(jobName);
List<String> taskList = cronTasks.get(jobKey);
if (null == taskList) {
taskList = new CopyOnWriteArrayList<>();
taskList.add(jobName);
cronTasks.put(jobKey, taskList);
return;
}
if (!taskList.contains(jobName)) {
taskList.add(jobName);
}
}
synchronized void remove(final String jobName) {
for (Entry<JobKey, List<String>> each : cronTasks.entrySet()) {
JobKey jobKey = each.getKey();
List<String> jobNames = each.getValue();
jobNames.remove(jobName);
if (jobNames.isEmpty()) {
cronTasks.remove(jobKey);
}
}
}
List<String> get(final JobKey jobKey) {
List<String> result = cronTasks.get(jobKey);
return null == result ? Collections.<String>emptyList() : result;
}
boolean containsKey(final JobKey jobKey) {
return cronTasks.containsKey(jobKey);
}
void removeAll() {
cronTasks.clear();
}
}
```
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.state.running;
import org.apache.shardingsphere.elasticjob.cloud.context.ExecutionType;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.config.job.CloudJobExecutionType;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.fixture.CloudJsonConstants;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.fixture.TaskNode;
import org.apache.shardingsphere.elasticjob.cloud.context.TaskContext;
import org.apache.shardingsphere.elasticjob.cloud.reg.base.CoordinatorRegistryCenter;
import org.hamcrest.core.Is;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.Arrays;
import java.util.Collections;
import java.util.UUID;
@RunWith(MockitoJUnitRunner.class)
public final class RunningServiceTest {
private TaskContext taskContext;
private TaskContext taskContextT;
@Mock
private CoordinatorRegistryCenter regCenter;
private RunningService runningService;
@Before
public void setUp() {
Mockito.when(regCenter.get("/config/job/test_job")).thenReturn(CloudJsonConstants.getJobJson(CloudJobExecutionType.DAEMON));
Mockito.when(regCenter.get("/config/job/test_job_t")).thenReturn(CloudJsonConstants.getJobJson("test_job_t"));
runningService = new RunningService(regCenter);
taskContext = TaskContext.from(TaskNode.builder().build().getTaskNodeValue());
taskContextT = TaskContext.from(TaskNode.builder().jobName("test_job_t").build().getTaskNodeValue());
runningService.add(taskContext);
runningService.add(taskContextT);
Assert.assertThat(runningService.getAllRunningDaemonTasks().size(), Is.is(1));
Assert.assertThat(runningService.getAllRunningTasks().size(), Is.is(2));
String path = RunningNode.getRunningTaskNodePath(taskContext.getMetaInfo().toString());
Mockito.verify(regCenter).isExisted(path);
Mockito.verify(regCenter).persist(path, taskContext.getId());
}
@After
public void tearDown() {
runningService.clear();
}
@Test
public void assertStart() {
TaskNode taskNode1 = TaskNode.builder().jobName("test_job").shardingItem(0).slaveId("111").type(ExecutionType.READY).uuid(UUID.randomUUID().toString()).build();
TaskNode taskNode2 = TaskNode.builder().jobName("test_job").shardingItem(1).slaveId("222").type(ExecutionType.FAILOVER).uuid(UUID.randomUUID().toString()).build();
Mockito.when(regCenter.getChildrenKeys(RunningNode.ROOT)).thenReturn(Collections.singletonList("test_job"));
Mockito.when(regCenter.getChildrenKeys(RunningNode.getRunningJobNodePath("test_job"))).thenReturn(Arrays.asList(taskNode1.getTaskNodePath(), taskNode2.getTaskNodePath()));
Mockito.when(regCenter.get(RunningNode.getRunningTaskNodePath(taskNode1.getTaskNodePath()))).thenReturn(taskNode1.getTaskNodeValue());
Mockito.when(regCenter.get(RunningNode.getRunningTaskNodePath(taskNode2.getTaskNodePath()))).thenReturn(taskNode2.getTaskNodeValue());
runningService.start();
Assert.assertThat(runningService.getAllRunningDaemonTasks().size(), Is.is(2));
}
@Test
public void assertAddWithoutData() {
Assert.assertThat(runningService.getRunningTasks("test_job").size(), Is.is(1));
Assert.assertThat(runningService.getRunningTasks("test_job").iterator().next(), Is.is(taskContext));
Assert.assertThat(runningService.getRunningTasks("test_job_t").size(), Is.is(1));
Assert.assertThat(runningService.getRunningTasks("test_job_t").iterator().next(), Is.is(taskContextT));
}
@Test
public void assertAddWithData() {
Mockito.when(regCenter.get("/config/job/other_job")).thenReturn(CloudJsonConstants.getJobJson("other_job"));
TaskNode taskNode = TaskNode.builder().jobName("other_job").build();
runningService.add(TaskContext.from(taskNode.getTaskNodeValue()));
Assert.assertThat(runningService.getRunningTasks("other_job").size(), Is.is(1));
Assert.assertThat(runningService.getRunningTasks("other_job").iterator().next(), Is.is(TaskContext.from(taskNode.getTaskNodeValue())));
}
@Test
public void assertUpdateIdle() {
runningService.updateIdle(taskContext, true);
Assert.assertThat(runningService.getRunningTasks("test_job").size(), Is.is(1));
Assert.assertTrue(runningService.getRunningTasks("test_job").iterator().next().isIdle());
}
@Test
public void assertRemoveByJobName() {
runningService.remove("test_job");
Assert.assertTrue(runningService.getRunningTasks("test_job").isEmpty());
Mockito.verify(regCenter).remove(RunningNode.getRunningJobNodePath("test_job"));
runningService.remove("test_job_t");
Assert.assertTrue(runningService.getRunningTasks("test_job_t").isEmpty());
}
@Test
public void assertRemoveByTaskContext() {
Mockito.when(regCenter.isExisted(RunningNode.getRunningJobNodePath("test_job"))).thenReturn(true);
Mockito.when(regCenter.getChildrenKeys(RunningNode.getRunningJobNodePath("test_job"))).thenReturn(Collections.<String>emptyList());
runningService.remove(taskContext);
Assert.assertTrue(runningService.getRunningTasks("test_job").isEmpty());
Mockito.verify(regCenter).remove(RunningNode.getRunningTaskNodePath(taskContext.getMetaInfo().toString()));
runningService.remove(taskContextT);
Assert.assertTrue(runningService.getRunningTasks("test_job_t").isEmpty());
}
@Test
public void assertIsJobRunning() {
Assert.assertTrue(runningService.isJobRunning("test_job"));
}
@Test
public void assertIsTaskRunning() {
Assert.assertTrue(runningService.isTaskRunning(TaskContext.MetaInfo.from(TaskNode.builder().build().getTaskNodePath())));
}
@Test
public void assertIsTaskNotRunning() {
Assert.assertFalse(runningService.isTaskRunning(TaskContext.MetaInfo.from(TaskNode.builder().shardingItem(2).build().getTaskNodePath())));
}
@Test
public void assertMappingOperate() {
String taskId = TaskNode.builder().build().getTaskNodeValue();
Assert.assertNull(runningService.popMapping(taskId));
runningService.addMapping(taskId, "localhost");
Assert.assertThat(runningService.popMapping(taskId), Is.is("localhost"));
Assert.assertNull(runningService.popMapping(taskId));
}
@Test
public void assertClear() {
Assert.assertFalse(runningService.getRunningTasks("test_job").isEmpty());
runningService.addMapping(TaskNode.builder().build().getTaskNodeValue(), "localhost");
runningService.clear();
Assert.assertTrue(runningService.getRunningTasks("test_job").isEmpty());
Assert.assertNull(runningService.popMapping(TaskNode.builder().build().getTaskNodeValue()));
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.state.running;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.config.job.CloudJobConfiguration;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.config.job.CloudJobConfigurationService;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.config.job.CloudJobExecutionType;
import org.apache.shardingsphere.elasticjob.cloud.context.TaskContext;
import org.apache.shardingsphere.elasticjob.cloud.reg.base.CoordinatorRegistryCenter;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterators;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
/**
* Running service.
*/
@RequiredArgsConstructor
public final class RunningService {
private static final int TASK_INITIAL_SIZE = 1024;
// TODO Using JMX to export
@Getter
private static final ConcurrentHashMap<String, Set<TaskContext>> RUNNING_TASKS = new ConcurrentHashMap<>(TASK_INITIAL_SIZE);
private static final ConcurrentHashMap<String, String> TASK_HOSTNAME_MAPPER = new ConcurrentHashMap<>(TASK_INITIAL_SIZE);
private final CoordinatorRegistryCenter regCenter;
private final CloudJobConfigurationService configurationService;
public RunningService(final CoordinatorRegistryCenter regCenter) {
this.regCenter = regCenter;
this.configurationService = new CloudJobConfigurationService(regCenter);
}
/**
* Start running queue service.
*/
public void start() {
clear();
List<String> jobKeys = regCenter.getChildrenKeys(RunningNode.ROOT);
for (String each : jobKeys) {
if (!configurationService.load(each).isPresent()) {
remove(each);
continue;
}
RUNNING_TASKS.put(each, Sets.newCopyOnWriteArraySet(Lists.transform(regCenter.getChildrenKeys(RunningNode.getRunningJobNodePath(each)), new Function<String, TaskContext>() {
@Override
public TaskContext apply(final String input) {
return TaskContext.from(regCenter.get(RunningNode.getRunningTaskNodePath(TaskContext.MetaInfo.from(input).toString())));
}
})));
}
}
/**
* Add task to running queue.
*
* @param taskContext task running context
*/
public void add(final TaskContext taskContext) {
if (!configurationService.load(taskContext.getMetaInfo().getJobName()).isPresent()) {
return;
}
getRunningTasks(taskContext.getMetaInfo().getJobName()).add(taskContext);
if (!isDaemon(taskContext.getMetaInfo().getJobName())) {
return;
}
String runningTaskNodePath = RunningNode.getRunningTaskNodePath(taskContext.getMetaInfo().toString());
if (!regCenter.isExisted(runningTaskNodePath)) {
regCenter.persist(runningTaskNodePath, taskContext.getId());
}
}
private boolean isDaemon(final String jobName) {
Optional<CloudJobConfiguration> cloudJobConfigurationOptional = configurationService.load(jobName);
return cloudJobConfigurationOptional.isPresent() && CloudJobExecutionType.DAEMON == cloudJobConfigurationOptional.get().getJobExecutionType();
}
/**
* Update task to idle state.
*
* @param taskContext task running context
* @param isIdle is idle
*/
public void updateIdle(final TaskContext taskContext, final boolean isIdle) {
synchronized (RUNNING_TASKS) {
Optional<TaskContext> taskContextOptional = findTask(taskContext);
if (taskContextOptional.isPresent()) {
taskContextOptional.get().setIdle(isIdle);
} else {
add(taskContext);
}
}
}
private Optional<TaskContext> findTask(final TaskContext taskContext) {
return Iterators.tryFind(getRunningTasks(taskContext.getMetaInfo().getJobName()).iterator(), new Predicate<TaskContext>() {
@Override
public boolean apply(final TaskContext input) {
return input.equals(taskContext);
}
});
}
/**
* Remove job from running queue.
*
* @param jobName job name
*/
public void remove(final String jobName) {
RUNNING_TASKS.remove(jobName);
if (!isDaemonOrAbsent(jobName)) {
return;
}
regCenter.remove(RunningNode.getRunningJobNodePath(jobName));
}
/**
* Remove task from running queue.
*
* @param taskContext task running context
*/
public void remove(final TaskContext taskContext) {
getRunningTasks(taskContext.getMetaInfo().getJobName()).remove(taskContext);
if (!isDaemonOrAbsent(taskContext.getMetaInfo().getJobName())) {
return;
}
regCenter.remove(RunningNode.getRunningTaskNodePath(taskContext.getMetaInfo().toString()));
String jobRootNode = RunningNode.getRunningJobNodePath(taskContext.getMetaInfo().getJobName());
if (regCenter.isExisted(jobRootNode) && regCenter.getChildrenKeys(jobRootNode).isEmpty()) {
regCenter.remove(jobRootNode);
}
}
private boolean isDaemonOrAbsent(final String jobName) {
Optional<CloudJobConfiguration> cloudJobConfigurationOptional = configurationService.load(jobName);
return !cloudJobConfigurationOptional.isPresent() || CloudJobExecutionType.DAEMON == cloudJobConfigurationOptional.get().getJobExecutionType();
}
/**
* Determine whether the job is running or not.
*
* @param jobName job name
* @return true is running, otherwise not
*/
public boolean isJobRunning(final String jobName) {
return !getRunningTasks(jobName).isEmpty();
}
/**
* Determine whether the task is running or not.
*
* @param metaInfo task meta info
* @return true is running, otherwise not
*/
public boolean isTaskRunning(final TaskContext.MetaInfo metaInfo) {
for (TaskContext each : getRunningTasks(metaInfo.getJobName())) {
if (each.getMetaInfo().equals(metaInfo)) {
return true;
}
}
return false;
}
/**
* Get running tasks by job name.
*
* @param jobName job name
* @return collection of the running tasks
*/
public Collection<TaskContext> getRunningTasks(final String jobName) {
Set<TaskContext> taskContexts = new CopyOnWriteArraySet<>();
Collection<TaskContext> result = RUNNING_TASKS.putIfAbsent(jobName, taskContexts);
return null == result ? taskContexts : result;
}
/**
* Get all running tasks.
*
* @return collection of all the running tasks
*/
public Map<String, Set<TaskContext>> getAllRunningTasks() {
Map<String, Set<TaskContext>> result = new HashMap<>(RUNNING_TASKS.size(), 1);
result.putAll(RUNNING_TASKS);
return result;
}
/**
* Get all running daemon tasks.
*
* @return collection of all the running daemon tasks
*/
public Set<TaskContext> getAllRunningDaemonTasks() {
List<String> jobKeys = regCenter.getChildrenKeys(RunningNode.ROOT);
for (String each : jobKeys) {
if (!RUNNING_TASKS.containsKey(each)) {
remove(each);
}
}
Set<TaskContext> result = Sets.newHashSet();
for (Map.Entry<String, Set<TaskContext>> each : RUNNING_TASKS.entrySet()) {
if (isDaemonOrAbsent(each.getKey())) {
result.addAll(each.getValue());
}
}
return result;
}
/**
* Add mapping of task primary key and hostname.
*
* @param taskId task primary key
* @param hostname host name
*/
public void addMapping(final String taskId, final String hostname) {
TASK_HOSTNAME_MAPPER.putIfAbsent(taskId, hostname);
}
/**
* Retrieve the hostname and then remove this task from the mapping.
*
* @param taskId task primary key
* @return the host name of the removed task
*/
public String popMapping(final String taskId) {
return TASK_HOSTNAME_MAPPER.remove(taskId);
}
/**
* Clear the running status.
*/
public void clear() {
RUNNING_TASKS.clear();
TASK_HOSTNAME_MAPPER.clear();
}
}
```
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.mesos;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.mesos.fixture.OfferBuilder;
import org.hamcrest.core.Is;
import org.junit.Assert;
import org.junit.Test;
public final class LeasesQueueTest {
private LeasesQueue leasesQueue = LeasesQueue.getInstance();
@Test
public void assertOperate() {
Assert.assertTrue(leasesQueue.drainTo().isEmpty());
leasesQueue.offer(OfferBuilder.createOffer("offer_1"));
leasesQueue.offer(OfferBuilder.createOffer("offer_2"));
Assert.assertThat(leasesQueue.drainTo().size(), Is.is(2));
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.mesos;
import com.netflix.fenzo.VirtualMachineLease;
import com.netflix.fenzo.plugins.VMLeaseObject;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.apache.mesos.Protos;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
/**
* Lease queue.
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class LeasesQueue {
private static final LeasesQueue INSTANCE = new LeasesQueue();
private final BlockingQueue<VirtualMachineLease> queue = new LinkedBlockingQueue<>();
/**
* Get instance.
*
* @return singleton instance
*/
public static LeasesQueue getInstance() {
return INSTANCE;
}
/**
* Offer resource to lease queue.
*
* @param offer resource
*/
public void offer(final Protos.Offer offer) {
queue.offer(new VMLeaseObject(offer));
}
/**
* Dump all the resources from lease queue.
*
* @return collection of resources
*/
public List<VirtualMachineLease> drainTo() {
List<VirtualMachineLease> result = new ArrayList<>(queue.size());
queue.drainTo(result);
return result;
}
}
```
|
```package org.apache.shardingsphere.elasticjob.cloud.event.rdb;
import org.hamcrest.core.Is;
import org.junit.Assert;
import org.junit.Test;
public final class JobEventRdbIdentityTest {
@Test
public void assertGetIdentity() {
Assert.assertThat(new JobEventRdbIdentity().getIdentity(), Is.is("rdb"));
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.shardingsphere.elasticjob.cloud.event.rdb;
import org.apache.shardingsphere.elasticjob.cloud.event.JobEventIdentity;
/**
* Job event RDB identity.
*/
public class JobEventRdbIdentity implements JobEventIdentity {
@Override
public String getIdentity() {
return "rdb";
}
}
```
|
```package org.apache.shardingsphere.elasticjob.cloud.event.fixture;
import org.apache.shardingsphere.elasticjob.cloud.event.JobEventIdentity;
public class TestJobEventIdentity implements JobEventIdentity {
@Override
public String getIdentity() {
return "test";
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.shardingsphere.elasticjob.cloud.event;
/**
* Job event identity.
*/
public interface JobEventIdentity {
/**
* Get identity.
*
* @return identity
*/
String getIdentity();
}
```
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.statistics;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import org.junit.Before;
import org.junit.Test;
public class TaskResultMetaDataTest {
private TaskResultMetaData metaData;
@Before
public void setUp() {
metaData = new TaskResultMetaData();
}
@Test
public void assertIncrementAndGet() {
for (int i = 0; i < 100; i++) {
assertThat(metaData.incrementAndGetSuccessCount(), is(i + 1));
assertThat(metaData.incrementAndGetFailedCount(), is(i + 1));
assertThat(metaData.getSuccessCount(), is(i + 1));
assertThat(metaData.getFailedCount(), is(i + 1));
}
}
@Test
public void assertReset() {
for (int i = 0; i < 100; i++) {
metaData.incrementAndGetSuccessCount();
metaData.incrementAndGetFailedCount();
}
metaData.reset();
assertThat(metaData.getSuccessCount(), is(0));
assertThat(metaData.getFailedCount(), is(0));
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.statistics;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Task result meta data.
*/
public final class TaskResultMetaData {
private final AtomicInteger successCount;
private final AtomicInteger failedCount;
public TaskResultMetaData() {
successCount = new AtomicInteger(0);
failedCount = new AtomicInteger(0);
}
/**
* Increase and get success count.
*
* @return success count
*/
public int incrementAndGetSuccessCount() {
return successCount.incrementAndGet();
}
/**
* Increase and get failed count.
*
* @return failed count
*/
public int incrementAndGetFailedCount() {
return failedCount.incrementAndGet();
}
/**
* Get success count.
*
* @return success count
*/
public int getSuccessCount() {
return successCount.get();
}
/**
* Get failed count.
*
* @return failed count
*/
public int getFailedCount() {
return failedCount.get();
}
/**
* Reset success and failed count.
*/
public void reset() {
successCount.set(0);
failedCount.set(0);
}
}
```
|
```package org.apache.shardingsphere.elasticjob.cloud.reg.exception;
import org.apache.zookeeper.KeeperException.ConnectionLossException;
import org.apache.zookeeper.KeeperException.NoNodeException;
import org.apache.zookeeper.KeeperException.NodeExistsException;
import org.junit.Ignore;
import org.junit.Test;
public final class RegExceptionHandlerTest {
@Test
@Ignore
// TODO throw InterruptedException will cause zookeeper TestingServer break. Ignore first, fix it later.
public void assertHandleExceptionWithInterruptedException() {
RegExceptionHandler.handleException(new InterruptedException());
}
@Test
public void assertHandleExceptionWithNull() {
RegExceptionHandler.handleException(null);
}
@Test(expected = RegException.class)
public void assertHandleExceptionWithOtherException() {
RegExceptionHandler.handleException(new RuntimeException());
}
@Test
public void assertHandleExceptionWithConnectionLossException() {
RegExceptionHandler.handleException(new ConnectionLossException());
}
@Test
public void assertHandleExceptionWithNoNodeException() {
RegExceptionHandler.handleException(new NoNodeException());
}
@Test
public void assertHandleExceptionWithNoNodeExistsException() {
RegExceptionHandler.handleException(new NodeExistsException());
}
@Test
public void assertHandleExceptionWithCausedConnectionLossException() {
RegExceptionHandler.handleException(new RuntimeException(new ConnectionLossException()));
}
@Test
public void assertHandleExceptionWithCausedNoNodeException() {
RegExceptionHandler.handleException(new RuntimeException(new NoNodeException()));
}
@Test
public void assertHandleExceptionWithCausedNoNodeExistsException() {
RegExceptionHandler.handleException(new RuntimeException(new NodeExistsException()));
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.shardingsphere.elasticjob.cloud.reg.exception;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.KeeperException.ConnectionLossException;
import org.apache.zookeeper.KeeperException.NoNodeException;
import org.apache.zookeeper.KeeperException.NodeExistsException;
/**
* Registry center exception handler.
*/
@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class RegExceptionHandler {
/**
* Handle exception.
*
* @param cause exception to be handled
*/
public static void handleException(final Exception cause) {
if (null == cause) {
return;
}
if (isIgnoredException(cause) || null != cause.getCause() && isIgnoredException(cause.getCause())) {
log.debug("Elastic job: ignored exception for: {}", cause.getMessage());
} else if (cause instanceof InterruptedException) {
Thread.currentThread().interrupt();
} else {
throw new RegException(cause);
}
}
private static boolean isIgnoredException(final Throwable cause) {
return cause instanceof ConnectionLossException || cause instanceof NoNodeException || cause instanceof NodeExistsException;
}
}
```
|
```package org.apache.shardingsphere.elasticjob.cloud.event.fixture;
public interface JobEventCaller {
/**
* Call method.
*/
void call();
}
```
|
Please help me generate a test for this class.
|
```package org.apache.shardingsphere.elasticjob.cloud.event;
/**
* Job event.
*/
public interface JobEvent {
/**
* Get job name.
*
* @return job name
*/
String getJobName();
}
```
|
```package org.apache.shardingsphere.elasticjob.cloud.executor;
import org.apache.shardingsphere.elasticjob.cloud.api.ElasticJob;
import org.apache.shardingsphere.elasticjob.cloud.api.JobType;
import org.apache.shardingsphere.elasticjob.cloud.context.ExecutionType;
import org.apache.shardingsphere.elasticjob.cloud.config.JobRootConfiguration;
import org.apache.shardingsphere.elasticjob.cloud.event.JobEventBus;
import org.apache.shardingsphere.elasticjob.cloud.event.type.JobExecutionEvent;
import org.apache.shardingsphere.elasticjob.cloud.exception.JobExecutionEnvironmentException;
import org.apache.shardingsphere.elasticjob.cloud.event.type.JobStatusTraceEvent;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.util.HashMap;
import java.util.Map;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.verify;
public class CloudJobFacadeTest {
private final ShardingContexts shardingContexts;
private final JobConfigurationContext jobConfig;
@Mock
private JobEventBus eventBus;
private final JobFacade jobFacade;
public CloudJobFacadeTest() {
MockitoAnnotations.initMocks(this);
shardingContexts = getShardingContexts();
jobConfig = new JobConfigurationContext(getJobConfigurationMap(JobType.SIMPLE, false));
jobFacade = new CloudJobFacade(shardingContexts, jobConfig, eventBus);
}
private ShardingContexts getShardingContexts() {
Map<Integer, String> shardingItemParameters = new HashMap<>(1, 1);
shardingItemParameters.put(0, "A");
return new ShardingContexts("fake_task_id", "test_job", 3, "", shardingItemParameters);
}
private Map<String, String> getJobConfigurationMap(final JobType jobType, final boolean streamingProcess) {
Map<String, String> result = new HashMap<>(10, 1);
result.put("jobName", "test_job");
result.put("jobClass", ElasticJob.class.getCanonicalName());
result.put("jobType", jobType.name());
result.put("streamingProcess", Boolean.toString(streamingProcess));
return result;
}
@Test
public void assertLoadJobRootConfiguration() {
assertThat(jobFacade.loadJobRootConfiguration(true), is((JobRootConfiguration) jobConfig));
}
@Test
public void assertCheckJobExecutionEnvironment() throws JobExecutionEnvironmentException {
jobFacade.checkJobExecutionEnvironment();
}
@Test
public void assertFailoverIfNecessary() {
jobFacade.failoverIfNecessary();
}
@Test
public void assertRegisterJobBegin() {
jobFacade.registerJobBegin(null);
}
@Test
public void assertRegisterJobCompleted() {
jobFacade.registerJobCompleted(null);
}
@Test
public void assertGetShardingContext() {
assertThat(jobFacade.getShardingContexts(), is(shardingContexts));
}
@Test
public void assertMisfireIfNecessary() {
jobFacade.misfireIfRunning(null);
}
@Test
public void assertClearMisfire() {
jobFacade.clearMisfire(null);
}
@Test
public void assertIsExecuteMisfired() {
assertFalse(jobFacade.isExecuteMisfired(null));
}
@Test
public void assertIsEligibleForJobRunningWhenIsNotDataflowJob() {
assertFalse(jobFacade.isEligibleForJobRunning());
}
@Test
public void assertIsEligibleForJobRunningWhenIsDataflowJobAndIsNotStreamingProcess() {
assertFalse(new CloudJobFacade(shardingContexts, new JobConfigurationContext(getJobConfigurationMap(JobType.DATAFLOW, false)), new JobEventBus()).isEligibleForJobRunning());
}
@Test
public void assertIsEligibleForJobRunningWhenIsDataflowJobAndIsStreamingProcess() {
assertTrue(new CloudJobFacade(shardingContexts, new JobConfigurationContext(getJobConfigurationMap(JobType.DATAFLOW, true)), new JobEventBus()).isEligibleForJobRunning());
}
@Test
public void assertIsNeedSharding() {
assertFalse(jobFacade.isNeedSharding());
}
@Test
public void assertBeforeJobExecuted() {
jobFacade.beforeJobExecuted(null);
}
@Test
public void assertAfterJobExecuted() {
jobFacade.afterJobExecuted(null);
}
@Test
public void assertPostJobExecutionEvent() {
JobExecutionEvent jobExecutionEvent = new JobExecutionEvent("fake_task_id", "test_job", JobExecutionEvent.ExecutionSource.NORMAL_TRIGGER, 0);
jobFacade.postJobExecutionEvent(jobExecutionEvent);
verify(eventBus).post(jobExecutionEvent);
}
@Test
public void assertPostJobStatusTraceEvent() {
jobFacade.postJobStatusTraceEvent(String.format("%s@-@0@-@%s@-@fake_slave_id@-@0", "test_job", ExecutionType.READY), JobStatusTraceEvent.State.TASK_RUNNING, "message is empty.");
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.shardingsphere.elasticjob.cloud.executor;
import org.apache.shardingsphere.elasticjob.cloud.config.JobRootConfiguration;
import org.apache.shardingsphere.elasticjob.cloud.config.dataflow.DataflowJobConfiguration;
import org.apache.shardingsphere.elasticjob.cloud.context.TaskContext;
import org.apache.shardingsphere.elasticjob.cloud.event.JobEventBus;
import org.apache.shardingsphere.elasticjob.cloud.event.type.JobExecutionEvent;
import org.apache.shardingsphere.elasticjob.cloud.event.type.JobStatusTraceEvent;
import org.apache.shardingsphere.elasticjob.cloud.exception.JobExecutionEnvironmentException;
import lombok.RequiredArgsConstructor;
import java.util.Collection;
/**
* Cloud job facade.
*/
@RequiredArgsConstructor
public final class CloudJobFacade implements JobFacade {
private final ShardingContexts shardingContexts;
private final JobConfigurationContext jobConfig;
private final JobEventBus jobEventBus;
@Override
public JobRootConfiguration loadJobRootConfiguration(final boolean fromCache) {
return jobConfig;
}
@Override
public void checkJobExecutionEnvironment() throws JobExecutionEnvironmentException {
}
@Override
public void failoverIfNecessary() {
}
@Override
public void registerJobBegin(final ShardingContexts shardingContexts) {
}
@Override
public void registerJobCompleted(final ShardingContexts shardingContexts) {
}
/**
* Get sharding contexts.
* @return sharding contexts
*/
public ShardingContexts getShardingContexts() {
return shardingContexts;
}
@Override
public boolean misfireIfRunning(final Collection<Integer> shardingItems) {
return false;
}
@Override
public void clearMisfire(final Collection<Integer> shardingItems) {
}
@Override
public boolean isExecuteMisfired(final Collection<Integer> shardingItems) {
return false;
}
@Override
public boolean isEligibleForJobRunning() {
return jobConfig.getTypeConfig() instanceof DataflowJobConfiguration && ((DataflowJobConfiguration) jobConfig.getTypeConfig()).isStreamingProcess();
}
@Override
public boolean isNeedSharding() {
return false;
}
@Override
public void beforeJobExecuted(final ShardingContexts shardingContexts) {
}
@Override
public void afterJobExecuted(final ShardingContexts shardingContexts) {
}
@Override
public void postJobExecutionEvent(final JobExecutionEvent jobExecutionEvent) {
jobEventBus.post(jobExecutionEvent);
}
@Override
public void postJobStatusTraceEvent(final String taskId, final JobStatusTraceEvent.State state, final String message) {
TaskContext taskContext = TaskContext.from(taskId);
jobEventBus.post(new JobStatusTraceEvent(taskContext.getMetaInfo().getJobName(), taskContext.getId(), taskContext.getSlaveId(),
JobStatusTraceEvent.Source.CLOUD_EXECUTOR, taskContext.getType(), String.valueOf(taskContext.getMetaInfo().getShardingItems()), state, message));
}
}
```
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.restful;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.ha.HANode;
import org.hamcrest.core.Is;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
import org.unitils.util.ReflectionUtils;
public class CloudOperationRestfulApiTest extends AbstractCloudRestfulApiTest {
@Test
public void assertExplicitReconcile() throws Exception {
ReflectionUtils.setFieldValue(new CloudOperationRestfulApi(), "lastReconcileTime", 0);
Assert.assertThat(RestfulTestsUtil.sentRequest("http://127.0.0.1:19000/api/operate/reconcile/explicit", "POST", ""), Is.is(204));
Assert.assertThat(RestfulTestsUtil.sentRequest("http://127.0.0.1:19000/api/operate/reconcile/explicit", "POST", ""), Is.is(500));
}
@Test
public void assertImplicitReconcile() throws Exception {
ReflectionUtils.setFieldValue(new CloudOperationRestfulApi(), "lastReconcileTime", 0);
Assert.assertThat(RestfulTestsUtil.sentRequest("http://127.0.0.1:19000/api/operate/reconcile/implicit", "POST", ""), Is.is(204));
Assert.assertThat(RestfulTestsUtil.sentRequest("http://127.0.0.1:19000/api/operate/reconcile/implicit", "POST", ""), Is.is(500));
}
@Test
public void assertSandbox() throws Exception {
Mockito.when(getRegCenter().getDirectly(HANode.FRAMEWORK_ID_NODE)).thenReturn("d8701508-41b7-471e-9b32-61cf824a660d-0000");
Assert.assertThat(RestfulTestsUtil.sentGetRequest("http://127.0.0.1:19000/api/operate/sandbox?appName=foo_app"), Is.is("[{\"hostname\":\"127.0.0.1\","
+ "\"path\":\"/slaves/d8701508-41b7-471e-9b32-61cf824a660d-S0/frameworks/d8701508-41b7-471e-9b32-61cf824a660d-0000/executors/foo_app@-@"
+ "d8701508-41b7-471e-9b32-61cf824a660d-S0/runs/53fb4af7-aee2-44f6-9e47-6f418d9f27e1\"}]"));
}
@Test
public void assertNoFrameworkSandbox() throws Exception {
Assert.assertThat(RestfulTestsUtil.sentGetRequest("http://127.0.0.1:19000/api/operate/sandbox?appName=foo_app"), Is.is("[]"));
Mockito.when(getRegCenter().getDirectly(HANode.FRAMEWORK_ID_NODE)).thenReturn("not-exists");
Assert.assertThat(RestfulTestsUtil.sentGetRequest("http://127.0.0.1:19000/api/operate/sandbox?appName=foo_app"), Is.is("[]"));
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.restful;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.mesos.MesosStateService;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.mesos.ReconcileService;
import org.apache.shardingsphere.elasticjob.cloud.reg.base.CoordinatorRegistryCenter;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.gson.JsonArray;
import lombok.extern.slf4j.Slf4j;
import org.codehaus.jettison.json.JSONException;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
/**
* Cloud operation restful api.
*/
@Path("/operate")
@Slf4j
public final class CloudOperationRestfulApi {
private static ReconcileService reconcileService;
private static final long RECONCILE_MILLIS_INTERVAL = 10 * 1000L;
private static MesosStateService mesosStateService;
private static long lastReconcileTime;
/**
* Init.
*
* @param regCenter registry center
* @param reconcileService reconcile service
*/
public static void init(final CoordinatorRegistryCenter regCenter, final ReconcileService reconcileService) {
CloudOperationRestfulApi.reconcileService = reconcileService;
CloudOperationRestfulApi.mesosStateService = new MesosStateService(regCenter);
}
/**
* Explicit reconcile service.
*/
@POST
@Path("/reconcile/explicit")
public void explicitReconcile() {
validReconcileInterval();
reconcileService.explicitReconcile();
}
/**
* Implicit reconcile service.
*/
@POST
@Path("/reconcile/implicit")
public void implicitReconcile() {
validReconcileInterval();
reconcileService.implicitReconcile();
}
private void validReconcileInterval() {
if (System.currentTimeMillis() < lastReconcileTime + RECONCILE_MILLIS_INTERVAL) {
throw new RuntimeException("Repeat explicitReconcile");
}
lastReconcileTime = System.currentTimeMillis();
}
/**
* Get sandbox of the cloud job by app name.
*
* @param appName application name
* @return sandbox info
* @throws JSONException parse json exception
*/
@GET
@Path("/sandbox")
public JsonArray sandbox(@QueryParam("appName") final String appName) throws JSONException {
Preconditions.checkArgument(!Strings.isNullOrEmpty(appName), "Lack param 'appName'");
return mesosStateService.sandbox(appName);
}
}
```
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.config.job;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.fixture.CloudJobConfigurationBuilder;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.fixture.CloudJsonConstants;
import org.apache.shardingsphere.elasticjob.cloud.reg.base.CoordinatorRegistryCenter;
import com.google.common.base.Optional;
import org.hamcrest.core.Is;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.Arrays;
import java.util.Collection;
@RunWith(MockitoJUnitRunner.class)
public final class CloudJobConfigurationServiceTest {
@Mock
private CoordinatorRegistryCenter regCenter;
@InjectMocks
private CloudJobConfigurationService configService;
@Test
public void assertAdd() {
CloudJobConfiguration jobConfig = CloudJobConfigurationBuilder.createCloudJobConfiguration("test_job");
configService.add(jobConfig);
Mockito.verify(regCenter).persist("/config/job/test_job", CloudJsonConstants.getJobJson());
}
@Test
public void assertUpdate() {
CloudJobConfiguration jobConfig = CloudJobConfigurationBuilder.createCloudJobConfiguration("test_job");
configService.update(jobConfig);
Mockito.verify(regCenter).update("/config/job/test_job", CloudJsonConstants.getJobJson());
}
@Test
public void assertAddSpringJob() {
CloudJobConfiguration jobConfig = CloudJobConfigurationBuilder.createCloudSpringJobConfiguration("test_spring_job");
configService.add(jobConfig);
Mockito.verify(regCenter).persist("/config/job/test_spring_job", CloudJsonConstants.getSpringJobJson());
}
@Test
public void assertLoadAllWithoutRootNode() {
Mockito.when(regCenter.isExisted("/config/job")).thenReturn(false);
Assert.assertTrue(configService.loadAll().isEmpty());
Mockito.verify(regCenter).isExisted("/config/job");
}
@Test
public void assertLoadAllWithRootNode() {
Mockito.when(regCenter.isExisted("/config/job")).thenReturn(true);
Mockito.when(regCenter.getChildrenKeys(CloudJobConfigurationNode.ROOT)).thenReturn(Arrays.asList("test_job_1", "test_job_2"));
Mockito.when(regCenter.get("/config/job/test_job_1")).thenReturn(CloudJsonConstants.getJobJson("test_job_1"));
Collection<CloudJobConfiguration> actual = configService.loadAll();
Assert.assertThat(actual.size(), Is.is(1));
Assert.assertThat(actual.iterator().next().getJobName(), Is.is("test_job_1"));
Mockito.verify(regCenter).isExisted("/config/job");
Mockito.verify(regCenter).getChildrenKeys("/config/job");
Mockito.verify(regCenter).get("/config/job/test_job_1");
Mockito.verify(regCenter).get("/config/job/test_job_2");
}
@Test
public void assertLoadWithoutConfig() {
Optional<CloudJobConfiguration> actual = configService.load("test_job");
Assert.assertFalse(actual.isPresent());
}
@Test
public void assertLoadWithConfig() {
Mockito.when(regCenter.get("/config/job/test_job")).thenReturn(CloudJsonConstants.getJobJson());
Optional<CloudJobConfiguration> actual = configService.load("test_job");
Assert.assertTrue(actual.isPresent());
Assert.assertThat(actual.get().getJobName(), Is.is("test_job"));
}
@Test
public void assertLoadWithSpringConfig() {
Mockito.when(regCenter.get("/config/job/test_spring_job")).thenReturn(CloudJsonConstants.getSpringJobJson());
Optional<CloudJobConfiguration> actual = configService.load("test_spring_job");
Assert.assertTrue(actual.isPresent());
Assert.assertThat(actual.get().getBeanName(), Is.is("springSimpleJob"));
Assert.assertThat(actual.get().getApplicationContext(), Is.is("applicationContext.xml"));
}
@Test
public void assertRemove() {
configService.remove("test_job");
Mockito.verify(regCenter).remove("/config/job/test_job");
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.config.job;
import com.google.common.base.Optional;
import org.apache.shardingsphere.elasticjob.cloud.reg.base.CoordinatorRegistryCenter;
import lombok.RequiredArgsConstructor;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
/**
* Cloud job configuration service.
*/
@RequiredArgsConstructor
public final class CloudJobConfigurationService {
private final CoordinatorRegistryCenter regCenter;
/**
* Add cloud job configuration.
*
* @param jobConfig cloud job configuration
*/
public void add(final CloudJobConfiguration jobConfig) {
regCenter.persist(CloudJobConfigurationNode.getRootNodePath(jobConfig.getJobName()), CloudJobConfigurationGsonFactory.toJson(jobConfig));
}
/**
* Update cloud job configuration.
*
* @param jobConfig cloud job configuration
*/
public void update(final CloudJobConfiguration jobConfig) {
regCenter.update(CloudJobConfigurationNode.getRootNodePath(jobConfig.getJobName()), CloudJobConfigurationGsonFactory.toJson(jobConfig));
}
/**
* Load all registered cloud job configurations.
*
* @return collection of the registered cloud job configuration
*/
public Collection<CloudJobConfiguration> loadAll() {
if (!regCenter.isExisted(CloudJobConfigurationNode.ROOT)) {
return Collections.emptyList();
}
List<String> jobNames = regCenter.getChildrenKeys(CloudJobConfigurationNode.ROOT);
Collection<CloudJobConfiguration> result = new ArrayList<>(jobNames.size());
for (String each : jobNames) {
Optional<CloudJobConfiguration> config = load(each);
if (config.isPresent()) {
result.add(config.get());
}
}
return result;
}
/**
* Load cloud job configuration by job name.
*
* @param jobName job name
* @return cloud job configuration
*/
public Optional<CloudJobConfiguration> load(final String jobName) {
return Optional.fromNullable(CloudJobConfigurationGsonFactory.fromJson(regCenter.get(CloudJobConfigurationNode.getRootNodePath(jobName))));
}
/**
* Remove cloud job configuration.
*
* @param jobName job name
*/
public void remove(final String jobName) {
regCenter.remove(CloudJobConfigurationNode.getRootNodePath(jobName));
}
}
```
|
```package org.apache.shardingsphere.elasticjob.cloud.reg.zookeeper;
import org.apache.shardingsphere.elasticjob.cloud.fixture.EmbedTestingServer;
import org.apache.shardingsphere.elasticjob.cloud.reg.base.ElectionCandidate;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryOneTime;
import org.apache.curator.test.KillSession;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
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() throws InterruptedException {
EmbedTestingServer.start();
}
@Test
@Ignore
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(), EmbedTestingServer.getConnectionString());
service.stop();
verify(anotherElectionCandidate).startLeadership();
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.shardingsphere.elasticjob.cloud.reg.zookeeper;
import org.apache.shardingsphere.elasticjob.cloud.reg.base.ElectionCandidate;
import org.apache.shardingsphere.elasticjob.cloud.exception.JobSystemException;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.leader.LeaderSelector;
import org.apache.curator.framework.recipes.leader.LeaderSelectorListenerAdapter;
import java.util.concurrent.CountDownLatch;
/**
* Use {@link LeaderSelector} to implement election service.
*/
@Slf4j
public final class ZookeeperElectionService {
private final CountDownLatch leaderLatch = new CountDownLatch(1);
private final LeaderSelector leaderSelector;
public ZookeeperElectionService(final String identity, final CuratorFramework client, final String electionPath, final ElectionCandidate electionCandidate) {
leaderSelector = new LeaderSelector(client, electionPath, new LeaderSelectorListenerAdapter() {
@Override
public void takeLeadership(final CuratorFramework client) throws Exception {
log.info("Elastic job: {} has leadership", identity);
try {
electionCandidate.startLeadership();
leaderLatch.await();
log.warn("Elastic job: {} lost leadership.", identity);
electionCandidate.stopLeadership();
} catch (final JobSystemException exception) {
log.error("Elastic job: Starting error", exception);
System.exit(1);
}
}
});
leaderSelector.autoRequeue();
leaderSelector.setId(identity);
}
/**
* Start election.
*/
public void start() {
log.debug("Elastic job: {} start to elect leadership", leaderSelector.getId());
leaderSelector.start();
}
/**
* Stop election.
*/
public void stop() {
log.info("Elastic job: stop leadership election");
leaderLatch.countDown();
try {
leaderSelector.close();
// CHECKSTYLE:OFF
} catch (final Exception ignored) {
}
// CHECKSTYLE:ON
}
}
```
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.restful;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.config.job.CloudJobExecutionType;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.fixture.TaskNode;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.state.running.RunningService;
import org.apache.shardingsphere.elasticjob.cloud.context.ExecutionType;
import org.apache.shardingsphere.elasticjob.cloud.event.rdb.JobEventRdbSearch;
import org.apache.shardingsphere.elasticjob.cloud.event.type.JobExecutionEvent;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.fixture.CloudAppJsonConstants;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.fixture.CloudJsonConstants;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.state.failover.FailoverTaskInfo;
import org.apache.shardingsphere.elasticjob.cloud.statistics.type.task.TaskResultStatistics;
import org.apache.shardingsphere.elasticjob.cloud.util.json.GsonFactory;
import org.apache.shardingsphere.elasticjob.cloud.context.TaskContext;
import org.apache.shardingsphere.elasticjob.cloud.event.type.JobStatusTraceEvent;
import org.apache.shardingsphere.elasticjob.cloud.statistics.type.job.JobExecutionTypeStatistics;
import org.apache.shardingsphere.elasticjob.cloud.statistics.type.job.JobTypeStatistics;
import com.google.common.collect.Lists;
import org.hamcrest.core.Is;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.unitils.util.ReflectionUtils;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
@RunWith(MockitoJUnitRunner.class)
public final class CloudJobRestfulApiTest extends AbstractCloudRestfulApiTest {
@Test
public void assertRegister() throws Exception {
Mockito.when(getRegCenter().get("/config/app/test_app")).thenReturn(CloudAppJsonConstants.getAppJson("test_app"));
Mockito.when(getRegCenter().isExisted("/config/job/test_job")).thenReturn(false);
Assert.assertThat(RestfulTestsUtil.sentRequest("http://127.0.0.1:19000/api/job/register", "POST", CloudJsonConstants.getJobJson()), Is.is(204));
Mockito.verify(getRegCenter()).persist("/config/job/test_job", CloudJsonConstants.getJobJson());
RestfulTestsUtil.sentRequest("http://127.0.0.1:19000/api/job/deregister", "DELETE", "test_job");
}
@Test
public void assertRegisterWithoutApp() throws Exception {
Mockito.when(getRegCenter().isExisted("/config/job/test_job")).thenReturn(false);
Assert.assertThat(RestfulTestsUtil.sentRequest("http://127.0.0.1:19000/api/job/register", "POST", CloudJsonConstants.getJobJson()), Is.is(500));
}
@Test
public void assertRegisterWithExistedName() throws Exception {
Mockito.when(getRegCenter().get("/config/app/test_app")).thenReturn(CloudAppJsonConstants.getAppJson("test_app"));
Mockito.when(getRegCenter().isExisted("/config/test_job")).thenReturn(false);
Assert.assertThat(RestfulTestsUtil.sentRequest("http://127.0.0.1:19000/api/job/register", "POST", CloudJsonConstants.getJobJson()), Is.is(204));
Mockito.when(getRegCenter().get("/config/job/test_job")).thenReturn(CloudJsonConstants.getJobJson());
Assert.assertThat(RestfulTestsUtil.sentRequest("http://127.0.0.1:19000/api/job/register", "POST", CloudJsonConstants.getJobJson()), Is.is(500));
RestfulTestsUtil.sentRequest("http://127.0.0.1:19000/api/job/deregister", "DELETE", "test_job");
}
@Test
public void assertRegisterWithBadRequest() throws Exception {
Mockito.when(getRegCenter().get("/config/app/test_app")).thenReturn(CloudAppJsonConstants.getAppJson("test_app"));
Assert.assertThat(RestfulTestsUtil.sentRequest("http://127.0.0.1:19000/api/job/register", "POST", "\"{\"jobName\":\"wrong_job\"}"), Is.is(500));
}
@Test
public void assertUpdate() throws Exception {
Mockito.when(getRegCenter().isExisted("/config/job/test_job")).thenReturn(true);
Mockito.when(getRegCenter().get("/config/job/test_job")).thenReturn(CloudJsonConstants.getJobJson());
Assert.assertThat(RestfulTestsUtil.sentRequest("http://127.0.0.1:19000/api/job/update", "PUT", CloudJsonConstants.getJobJson()), Is.is(204));
Mockito.verify(getRegCenter()).update("/config/job/test_job", CloudJsonConstants.getJobJson());
RestfulTestsUtil.sentRequest("http://127.0.0.1:19000/api/job/deregister", "DELETE", "test_job");
}
@Test
public void assertDeregister() throws Exception {
Mockito.when(getRegCenter().isExisted("/config/job/test_job")).thenReturn(false);
Assert.assertThat(RestfulTestsUtil.sentRequest("http://127.0.0.1:19000/api/job/deregister", "DELETE", "test_job"), Is.is(204));
Mockito.verify(getRegCenter(), Mockito.times(3)).get("/config/job/test_job");
}
@Test
public void assertTriggerWithDaemonJob() throws Exception {
Mockito.when(getRegCenter().get("/config/job/test_job")).thenReturn(CloudJsonConstants.getJobJson(CloudJobExecutionType.DAEMON));
Assert.assertThat(RestfulTestsUtil.sentRequest("http://127.0.0.1:19000/api/job/trigger", "POST", "test_job"), Is.is(500));
}
@Test
public void assertTriggerWithTransientJob() throws Exception {
Mockito.when(getRegCenter().get("/config/job/test_job")).thenReturn(CloudJsonConstants.getJobJson());
Assert.assertThat(RestfulTestsUtil.sentRequest("http://127.0.0.1:19000/api/job/trigger", "POST", "test_job"), Is.is(204));
}
@Test
public void assertDetail() throws Exception {
Mockito.when(getRegCenter().get("/config/job/test_job")).thenReturn(CloudJsonConstants.getJobJson());
Assert.assertThat(RestfulTestsUtil.sentGetRequest("http://127.0.0.1:19000/api/job/jobs/test_job"), Is.is(CloudJsonConstants.getJobJson()));
Mockito.verify(getRegCenter()).get("/config/job/test_job");
}
@Test
public void assertDetailWithNotExistedJob() throws Exception {
Assert.assertThat(RestfulTestsUtil.sentRequest("http://127.0.0.1:19000/api/job/jobs/notExistedJobName", "GET", ""), Is.is(404));
}
@Test
public void assertFindAllJobs() throws Exception {
Mockito.when(getRegCenter().isExisted("/config/job")).thenReturn(true);
Mockito.when(getRegCenter().getChildrenKeys("/config/job")).thenReturn(Lists.newArrayList("test_job"));
Mockito.when(getRegCenter().get("/config/job/test_job")).thenReturn(CloudJsonConstants.getJobJson());
Assert.assertThat(RestfulTestsUtil.sentGetRequest("http://127.0.0.1:19000/api/job/jobs"), Is.is("[" + CloudJsonConstants.getJobJson() + "]"));
Mockito.verify(getRegCenter()).isExisted("/config/job");
Mockito.verify(getRegCenter()).getChildrenKeys("/config/job");
Mockito.verify(getRegCenter()).get("/config/job/test_job");
}
@Test
public void assertFindAllRunningTasks() throws Exception {
RunningService runningService = new RunningService(getRegCenter());
TaskContext actualTaskContext = TaskContext.from(TaskNode.builder().build().getTaskNodeValue());
Mockito.when(getRegCenter().get("/config/job/" + actualTaskContext.getMetaInfo().getJobName())).thenReturn(CloudJsonConstants.getJobJson());
runningService.add(actualTaskContext);
Assert.assertThat(RestfulTestsUtil.sentGetRequest("http://127.0.0.1:19000/api/job/tasks/running"), Is.is(GsonFactory.getGson().toJson(Lists.newArrayList(actualTaskContext))));
}
@Test
public void assertFindAllReadyTasks() throws Exception {
Mockito.when(getRegCenter().isExisted("/state/ready")).thenReturn(true);
Mockito.when(getRegCenter().getChildrenKeys("/state/ready")).thenReturn(Lists.newArrayList("test_job"));
Mockito.when(getRegCenter().get("/state/ready/test_job")).thenReturn("1");
Map<String, String> expectedMap = new HashMap<>();
expectedMap.put("jobName", "test_job");
expectedMap.put("times", "1");
@SuppressWarnings("unchecked")
Collection<Map<String, String>> expectedResult = Lists.newArrayList(expectedMap);
Assert.assertThat(RestfulTestsUtil.sentGetRequest("http://127.0.0.1:19000/api/job/tasks/ready"), Is.is(GsonFactory.getGson().toJson(expectedResult)));
Mockito.verify(getRegCenter()).isExisted("/state/ready");
Mockito.verify(getRegCenter()).getChildrenKeys("/state/ready");
Mockito.verify(getRegCenter()).get("/state/ready/test_job");
}
@Test
public void assertFindAllFailoverTasks() throws Exception {
Mockito.when(getRegCenter().isExisted("/state/failover")).thenReturn(true);
Mockito.when(getRegCenter().getChildrenKeys("/state/failover")).thenReturn(Lists.newArrayList("test_job"));
Mockito.when(getRegCenter().getChildrenKeys("/state/failover/test_job")).thenReturn(Lists.newArrayList("test_job@-@0"));
String originalTaskId = UUID.randomUUID().toString();
Mockito.when(getRegCenter().get("/state/failover/test_job/test_job@-@0")).thenReturn(originalTaskId);
FailoverTaskInfo expectedFailoverTask = new FailoverTaskInfo(TaskContext.MetaInfo.from("test_job@-@0"), originalTaskId);
Collection<FailoverTaskInfo> expectedResult = Lists.newArrayList(expectedFailoverTask);
Assert.assertThat(RestfulTestsUtil.sentGetRequest("http://127.0.0.1:19000/api/job/tasks/failover"), Is.is(GsonFactory.getGson().toJson(expectedResult)));
Mockito.verify(getRegCenter()).isExisted("/state/failover");
Mockito.verify(getRegCenter()).getChildrenKeys("/state/failover");
Mockito.verify(getRegCenter()).getChildrenKeys("/state/failover/test_job");
Mockito.verify(getRegCenter()).get("/state/failover/test_job/test_job@-@0");
}
@Test
public void assertFindJobExecutionEventsWhenNotConfigRDB() throws Exception {
ReflectionUtils.setFieldValue(CloudJobRestfulApi.class, CloudJobRestfulApi.class.getDeclaredField("jobEventRdbSearch"), null);
Assert.assertThat(RestfulTestsUtil.sentGetRequest("http://127.0.0.1:19000/api/job/events/executions"), Is.is(GsonFactory.getGson().toJson(new JobEventRdbSearch.Result<>(0,
Collections.<JobExecutionEvent>emptyList()))));
}
@Test
public void assertFindJobExecutionEvents() throws Exception {
ReflectionUtils.setFieldValue(CloudJobRestfulApi.class, CloudJobRestfulApi.class.getDeclaredField("jobEventRdbSearch"), getJobEventRdbSearch());
JobExecutionEvent jobExecutionEvent = new JobExecutionEvent("fake_task_id", "test_job", JobExecutionEvent.ExecutionSource.NORMAL_TRIGGER, 0);
Mockito.when(getJobEventRdbSearch().findJobExecutionEvents(Mockito.any(JobEventRdbSearch.Condition.class))).thenReturn(new JobEventRdbSearch.Result<>(0,
Lists.newArrayList(jobExecutionEvent)));
Assert.assertThat(RestfulTestsUtil.sentGetRequest("http://127.0.0.1:19000/api/job/events/executions?" + buildFindJobEventsQueryParameter()),
Is.is(GsonFactory.getGson().toJson(new JobEventRdbSearch.Result<>(0, Lists.newArrayList(jobExecutionEvent)))));
Mockito.verify(getJobEventRdbSearch()).findJobExecutionEvents(Mockito.any(JobEventRdbSearch.Condition.class));
}
@Test
public void assertFindJobStatusTraceEventEventsWhenNotConfigRDB() throws Exception {
ReflectionUtils.setFieldValue(CloudJobRestfulApi.class, CloudJobRestfulApi.class.getDeclaredField("jobEventRdbSearch"), null);
Assert.assertThat(RestfulTestsUtil.sentGetRequest("http://127.0.0.1:19000/api/job/events/statusTraces"), Is.is(GsonFactory.getGson().toJson(new JobEventRdbSearch.Result<>(0,
Collections.<JobExecutionEvent>emptyList()))));
}
@Test
public void assertFindJobStatusTraceEvent() throws Exception {
ReflectionUtils.setFieldValue(CloudJobRestfulApi.class, CloudJobRestfulApi.class.getDeclaredField("jobEventRdbSearch"), getJobEventRdbSearch());
JobStatusTraceEvent jobStatusTraceEvent = new JobStatusTraceEvent(
"test-job", "fake_task_id", "fake_slave_id", JobStatusTraceEvent.Source.LITE_EXECUTOR, ExecutionType.READY, "0", JobStatusTraceEvent.State.TASK_RUNNING, "message is empty.");
Mockito.when(getJobEventRdbSearch().findJobStatusTraceEvents(Mockito.any(JobEventRdbSearch.Condition.class))).thenReturn(new JobEventRdbSearch.Result<>(0,
Lists.newArrayList(jobStatusTraceEvent)));
Assert.assertThat(RestfulTestsUtil.sentGetRequest("http://127.0.0.1:19000/api/job/events/statusTraces?" + buildFindJobEventsQueryParameter()),
Is.is(GsonFactory.getGson().toJson(new JobEventRdbSearch.Result<>(0, Lists.newArrayList(jobStatusTraceEvent)))));
Mockito.verify(getJobEventRdbSearch()).findJobStatusTraceEvents(Mockito.any(JobEventRdbSearch.Condition.class));
}
private String buildFindJobEventsQueryParameter() throws UnsupportedEncodingException {
return "per_page=10&page=1&sort=jobName&order=DESC&jobName=test_job"
+ "&startTime=" + URLEncoder.encode("2016-12-26 10:00:00", "UTF-8") + "&endTime=" + URLEncoder.encode("2016-12-26 10:00:00", "UTF-8");
}
@Test
public void assertGetTaskResultStatistics() throws Exception {
Assert.assertThat(RestfulTestsUtil.sentGetRequest("http://127.0.0.1:19000/api/job/statistics/tasks/results"),
Is.is(GsonFactory.getGson().toJson(Collections.emptyList())));
}
@Test
public void assertGetTaskResultStatisticsWithSinceParameter() throws Exception {
Assert.assertThat(RestfulTestsUtil.sentGetRequest("http://127.0.0.1:19000/api/job/statistics/tasks/results?since=last24hours"),
Is.is(GsonFactory.getGson().toJson(Collections.emptyList())));
}
@Test
public void assertGetTaskResultStatisticsWithPathParameter() throws Exception {
String[] parameters = {"online", "lastWeek", "lastHour", "lastMinute"};
for (String each : parameters) {
String result = RestfulTestsUtil.sentGetRequest("http://127.0.0.1:19000/api/job/statistics/tasks/results/" + each);
TaskResultStatistics taskResultStatistics = GsonFactory.getGson().fromJson(result, TaskResultStatistics.class);
Assert.assertThat(taskResultStatistics.getSuccessCount(), Is.is(0));
Assert.assertThat(taskResultStatistics.getFailedCount(), Is.is(0));
}
}
@Test
public void assertGetTaskResultStatisticsWithErrorPathParameter() throws Exception {
String result = RestfulTestsUtil.sentGetRequest("http://127.0.0.1:19000/api/job/statistics/tasks/results/errorPath");
TaskResultStatistics taskResultStatistics = GsonFactory.getGson().fromJson(result, TaskResultStatistics.class);
Assert.assertThat(taskResultStatistics.getSuccessCount(), Is.is(0));
Assert.assertThat(taskResultStatistics.getFailedCount(), Is.is(0));
}
@Test
public void assertGetJobTypeStatistics() throws Exception {
String result = RestfulTestsUtil.sentGetRequest("http://127.0.0.1:19000/api/job/statistics/jobs/type");
JobTypeStatistics jobTypeStatistics = GsonFactory.getGson().fromJson(result, JobTypeStatistics.class);
Assert.assertThat(jobTypeStatistics.getSimpleJobCount(), Is.is(0));
Assert.assertThat(jobTypeStatistics.getDataflowJobCount(), Is.is(0));
Assert.assertThat(jobTypeStatistics.getScriptJobCount(), Is.is(0));
}
@Test
public void assertGetJobExecutionTypeStatistics() throws Exception {
String result = RestfulTestsUtil.sentGetRequest("http://127.0.0.1:19000/api/job/statistics/jobs/executionType");
JobExecutionTypeStatistics jobExecutionTypeStatistics = GsonFactory.getGson().fromJson(result, JobExecutionTypeStatistics.class);
Assert.assertThat(jobExecutionTypeStatistics.getDaemonJobCount(), Is.is(0));
Assert.assertThat(jobExecutionTypeStatistics.getTransientJobCount(), Is.is(0));
}
@Test
public void assertFindTaskRunningStatistics() throws Exception {
Assert.assertThat(RestfulTestsUtil.sentGetRequest("http://127.0.0.1:19000/api/job/statistics/tasks/running"),
Is.is(GsonFactory.getGson().toJson(Collections.emptyList())));
}
@Test
public void assertFindTaskRunningStatisticsWeekly() throws Exception {
Assert.assertThat(RestfulTestsUtil.sentGetRequest("http://127.0.0.1:19000/api/job/statistics/tasks/running?since=lastWeek"),
Is.is(GsonFactory.getGson().toJson(Collections.emptyList())));
}
@Test
public void assertFindJobRunningStatistics() throws Exception {
Assert.assertThat(RestfulTestsUtil.sentGetRequest("http://127.0.0.1:19000/api/job/statistics/jobs/running"),
Is.is(GsonFactory.getGson().toJson(Collections.emptyList())));
}
@Test
public void assertFindJobRunningStatisticsWeekly() throws Exception {
Assert.assertThat(RestfulTestsUtil.sentGetRequest("http://127.0.0.1:19000/api/job/statistics/jobs/running?since=lastWeek"),
Is.is(GsonFactory.getGson().toJson(Collections.emptyList())));
}
@Test
public void assertFindJobRegisterStatisticsSinceOnline() throws Exception {
Assert.assertThat(RestfulTestsUtil.sentGetRequest("http://127.0.0.1:19000/api/job/statistics/jobs/register"),
Is.is(GsonFactory.getGson().toJson(Collections.emptyList())));
}
@Test
public void assertIsDisabled() throws Exception {
Mockito.when(getRegCenter().isExisted("/state/disable/job/test_job")).thenReturn(true);
Assert.assertThat(RestfulTestsUtil.sentGetRequest("http://127.0.0.1:19000/api/job/test_job/disable"), Is.is("true"));
}
@Test
public void assertDisable() throws Exception {
Mockito.when(getRegCenter().isExisted("/config/job")).thenReturn(true);
Mockito.when(getRegCenter().getChildrenKeys("/config/job")).thenReturn(Lists.newArrayList("test_job"));
Mockito.when(getRegCenter().get("/config/app/test_app")).thenReturn(CloudAppJsonConstants.getAppJson("test_app"));
Mockito.when(getRegCenter().get("/config/job/test_job")).thenReturn(CloudJsonConstants.getJobJson());
Assert.assertThat(RestfulTestsUtil.sentRequest("http://127.0.0.1:19000/api/job/test_job/disable", "POST"), Is.is(204));
Mockito.verify(getRegCenter()).persist("/state/disable/job/test_job", "test_job");
}
@Test
public void assertEnable() throws Exception {
Mockito.when(getRegCenter().isExisted("/config/job")).thenReturn(true);
Mockito.when(getRegCenter().getChildrenKeys("/config/job")).thenReturn(Lists.newArrayList("test_job"));
Mockito.when(getRegCenter().get("/config/app/test_app")).thenReturn(CloudAppJsonConstants.getAppJson("test_app"));
Mockito.when(getRegCenter().get("/config/job/test_job")).thenReturn(CloudJsonConstants.getJobJson());
Assert.assertThat(RestfulTestsUtil.sentRequest("http://127.0.0.1:19000/api/job/test_job/enable", "POST", "test_job"), Is.is(204));
Mockito.verify(getRegCenter()).remove("/state/disable/job/test_job");
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.restful;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.config.job.CloudJobConfiguration;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.statistics.StatisticManager;
import org.apache.shardingsphere.elasticjob.cloud.event.rdb.JobEventRdbConfiguration;
import org.apache.shardingsphere.elasticjob.cloud.event.rdb.JobEventRdbSearch;
import org.apache.shardingsphere.elasticjob.cloud.event.type.JobExecutionEvent;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.config.job.CloudJobConfigurationGsonFactory;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.config.job.CloudJobConfigurationService;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.config.job.CloudJobExecutionType;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.env.BootstrapEnvironment;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.mesos.FacadeService;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.producer.ProducerManager;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.state.failover.FailoverTaskInfo;
import org.apache.shardingsphere.elasticjob.cloud.statistics.StatisticInterval;
import org.apache.shardingsphere.elasticjob.cloud.statistics.type.job.JobRegisterStatistics;
import org.apache.shardingsphere.elasticjob.cloud.statistics.type.task.TaskResultStatistics;
import org.apache.shardingsphere.elasticjob.cloud.context.TaskContext;
import org.apache.shardingsphere.elasticjob.cloud.event.type.JobStatusTraceEvent;
import org.apache.shardingsphere.elasticjob.cloud.exception.JobSystemException;
import org.apache.shardingsphere.elasticjob.cloud.reg.base.CoordinatorRegistryCenter;
import org.apache.shardingsphere.elasticjob.cloud.statistics.type.job.JobExecutionTypeStatistics;
import org.apache.shardingsphere.elasticjob.cloud.statistics.type.job.JobRunningStatistics;
import org.apache.shardingsphere.elasticjob.cloud.statistics.type.job.JobTypeStatistics;
import org.apache.shardingsphere.elasticjob.cloud.statistics.type.task.TaskRunningStatistics;
import org.apache.shardingsphere.elasticjob.cloud.util.json.GsonFactory;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import lombok.extern.slf4j.Slf4j;
import org.codehaus.jettison.json.JSONException;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/**
* Cloud job restful api.
*/
@Path("/job")
@Slf4j
public final class CloudJobRestfulApi {
private static CoordinatorRegistryCenter regCenter;
private static JobEventRdbSearch jobEventRdbSearch;
private static ProducerManager producerManager;
private final CloudJobConfigurationService configService;
private final FacadeService facadeService;
private final StatisticManager statisticManager;
public CloudJobRestfulApi() {
Preconditions.checkNotNull(regCenter);
configService = new CloudJobConfigurationService(regCenter);
facadeService = new FacadeService(regCenter);
Optional<JobEventRdbConfiguration> jobEventRdbConfiguration = Optional.absent();
statisticManager = StatisticManager.getInstance(regCenter, jobEventRdbConfiguration);
}
/**
* Init.
*
* @param regCenter registry center
* @param producerManager producer manager
*/
public static void init(final CoordinatorRegistryCenter regCenter, final ProducerManager producerManager) {
CloudJobRestfulApi.regCenter = regCenter;
CloudJobRestfulApi.producerManager = producerManager;
GsonFactory.registerTypeAdapter(CloudJobConfiguration.class, new CloudJobConfigurationGsonFactory.CloudJobConfigurationGsonTypeAdapter());
Optional<JobEventRdbConfiguration> jobEventRdbConfig = BootstrapEnvironment.getInstance().getJobEventRdbConfiguration();
if (jobEventRdbConfig.isPresent()) {
jobEventRdbSearch = new JobEventRdbSearch(jobEventRdbConfig.get().getDataSource());
} else {
jobEventRdbSearch = null;
}
}
/**
* Register cloud job.
*
* @param jobConfig cloud job configuration
*/
@POST
@Path("/register")
@Consumes(MediaType.APPLICATION_JSON)
public void register(final CloudJobConfiguration jobConfig) {
producerManager.register(jobConfig);
}
/**
* Update cloud job.
*
* @param jobConfig cloud job configuration
*/
@PUT
@Path("/update")
@Consumes(MediaType.APPLICATION_JSON)
public void update(final CloudJobConfiguration jobConfig) {
producerManager.update(jobConfig);
}
/**
* Deregister cloud job.
*
* @param jobName job name
*/
@DELETE
@Path("/deregister")
@Consumes(MediaType.APPLICATION_JSON)
public void deregister(final String jobName) {
producerManager.deregister(jobName);
}
/**
* Check whether the cloud job is disabled or not.
*
* @param jobName job name
* @return true is disabled, otherwise not
* @throws JSONException parse json exception
*/
@GET
@Path("/{jobName}/disable")
@Produces(MediaType.APPLICATION_JSON)
public boolean isDisabled(@PathParam("jobName") final String jobName) throws JSONException {
return facadeService.isJobDisabled(jobName);
}
/**
* Enable cloud job.
*
* @param jobName job name
* @throws JSONException parse json exception
*/
@POST
@Path("/{jobName}/enable")
public void enable(@PathParam("jobName") final String jobName) throws JSONException {
Optional<CloudJobConfiguration> configOptional = configService.load(jobName);
if (configOptional.isPresent()) {
facadeService.enableJob(jobName);
producerManager.reschedule(jobName);
}
}
/**
* Disable cloud job.
*
* @param jobName job name
*/
@POST
@Path("/{jobName}/disable")
public void disable(@PathParam("jobName") final String jobName) {
if (configService.load(jobName).isPresent()) {
facadeService.disableJob(jobName);
producerManager.unschedule(jobName);
}
}
/**
* Trigger job once.
*
* @param jobName job name
*/
@POST
@Path("/trigger")
@Consumes(MediaType.APPLICATION_JSON)
public void trigger(final String jobName) {
Optional<CloudJobConfiguration> config = configService.load(jobName);
if (config.isPresent() && CloudJobExecutionType.DAEMON == config.get().getJobExecutionType()) {
throw new JobSystemException("Daemon job '%s' cannot support trigger.", jobName);
}
facadeService.addTransient(jobName);
}
/**
* Query job detail.
*
* @param jobName job name
* @return the job detail
*/
@GET
@Path("/jobs/{jobName}")
@Consumes(MediaType.APPLICATION_JSON)
public Response detail(@PathParam("jobName") final String jobName) {
Optional<CloudJobConfiguration> jobConfig = configService.load(jobName);
if (!jobConfig.isPresent()) {
return Response.status(Response.Status.NOT_FOUND).build();
}
return Response.ok(jobConfig.get()).build();
}
/**
* Find all jobs.
*
* @return all jobs
*/
@GET
@Path("/jobs")
@Consumes(MediaType.APPLICATION_JSON)
public Collection<CloudJobConfiguration> findAllJobs() {
return configService.loadAll();
}
/**
* Find all running tasks.
*
* @return all running tasks
*/
@GET
@Path("tasks/running")
@Consumes(MediaType.APPLICATION_JSON)
public Collection<TaskContext> findAllRunningTasks() {
List<TaskContext> result = new LinkedList<>();
for (Set<TaskContext> each : facadeService.getAllRunningTasks().values()) {
result.addAll(each);
}
return result;
}
/**
* Find all ready tasks.
*
* @return collection of all ready tasks
*/
@GET
@Path("tasks/ready")
@Consumes(MediaType.APPLICATION_JSON)
public Collection<Map<String, String>> findAllReadyTasks() {
Map<String, Integer> readyTasks = facadeService.getAllReadyTasks();
List<Map<String, String>> result = new ArrayList<>(readyTasks.size());
for (Entry<String, Integer> each : readyTasks.entrySet()) {
Map<String, String> oneTask = new HashMap<>(2, 1);
oneTask.put("jobName", each.getKey());
oneTask.put("times", String.valueOf(each.getValue()));
result.add(oneTask);
}
return result;
}
/**
* Find all failover tasks.
*
* @return collection of all the failover tasks
*/
@GET
@Path("tasks/failover")
@Consumes(MediaType.APPLICATION_JSON)
public Collection<FailoverTaskInfo> findAllFailoverTasks() {
List<FailoverTaskInfo> result = new LinkedList<>();
for (Collection<FailoverTaskInfo> each : facadeService.getAllFailoverTasks().values()) {
result.addAll(each);
}
return result;
}
/**
* Find job execution events.
*
* @param info uri info
* @return job execution event
* @throws ParseException parse exception
*/
@GET
@Path("events/executions")
@Consumes(MediaType.APPLICATION_JSON)
public JobEventRdbSearch.Result<JobExecutionEvent> findJobExecutionEvents(@Context final UriInfo info) throws ParseException {
if (!isRdbConfigured()) {
return new JobEventRdbSearch.Result<>(0, Collections.<JobExecutionEvent>emptyList());
}
return jobEventRdbSearch.findJobExecutionEvents(buildCondition(info, new String[]{"jobName", "taskId", "ip", "isSuccess"}));
}
/**
* Find job status trace events.
*
* @param info uri info
* @return job status trace event
* @throws ParseException parse exception
*/
@GET
@Path("events/statusTraces")
@Consumes(MediaType.APPLICATION_JSON)
public JobEventRdbSearch.Result<JobStatusTraceEvent> findJobStatusTraceEvents(@Context final UriInfo info) throws ParseException {
if (!isRdbConfigured()) {
return new JobEventRdbSearch.Result<>(0, Collections.<JobStatusTraceEvent>emptyList());
}
return jobEventRdbSearch.findJobStatusTraceEvents(buildCondition(info, new String[]{"jobName", "taskId", "slaveId", "source", "executionType", "state"}));
}
private boolean isRdbConfigured() {
return null != jobEventRdbSearch;
}
private JobEventRdbSearch.Condition buildCondition(final UriInfo info, final String[] params) throws ParseException {
int perPage = 10;
int page = 1;
if (!Strings.isNullOrEmpty(info.getQueryParameters().getFirst("per_page"))) {
perPage = Integer.parseInt(info.getQueryParameters().getFirst("per_page"));
}
if (!Strings.isNullOrEmpty(info.getQueryParameters().getFirst("page"))) {
page = Integer.parseInt(info.getQueryParameters().getFirst("page"));
}
String sort = info.getQueryParameters().getFirst("sort");
String order = info.getQueryParameters().getFirst("order");
Date startTime = null;
Date endTime = null;
Map<String, Object> fields = getQueryParameters(info, params);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
if (!Strings.isNullOrEmpty(info.getQueryParameters().getFirst("startTime"))) {
startTime = simpleDateFormat.parse(info.getQueryParameters().getFirst("startTime"));
}
if (!Strings.isNullOrEmpty(info.getQueryParameters().getFirst("endTime"))) {
endTime = simpleDateFormat.parse(info.getQueryParameters().getFirst("endTime"));
}
return new JobEventRdbSearch.Condition(perPage, page, sort, order, startTime, endTime, fields);
}
private Map<String, Object> getQueryParameters(final UriInfo info, final String[] params) {
final Map<String, Object> result = new HashMap<>();
for (String each : params) {
if (!Strings.isNullOrEmpty(info.getQueryParameters().getFirst(each))) {
result.put(each, info.getQueryParameters().getFirst(each));
}
}
return result;
}
/**
* Find task result statistics.
*
* @param since time span
* @return task result statistics
*/
@GET
@Path("/statistics/tasks/results")
@Consumes(MediaType.APPLICATION_JSON)
public List<TaskResultStatistics> findTaskResultStatistics(@QueryParam("since") final String since) {
if ("last24hours".equals(since)) {
return statisticManager.findTaskResultStatisticsDaily();
} else {
return Collections.emptyList();
}
}
/**
* Get task result statistics.
*
* @param period time period
* @return task result statistics
*/
@GET
@Path("/statistics/tasks/results/{period}")
@Consumes(MediaType.APPLICATION_JSON)
public TaskResultStatistics getTaskResultStatistics(@PathParam("period") final String period) {
if ("online".equals(period)) {
return statisticManager.getTaskResultStatisticsSinceOnline();
} else if ("lastWeek".equals(period)) {
return statisticManager.getTaskResultStatisticsWeekly();
} else if ("lastHour".equals(period)) {
return statisticManager.findLatestTaskResultStatistics(StatisticInterval.HOUR);
} else if ("lastMinute".equals(period)) {
return statisticManager.findLatestTaskResultStatistics(StatisticInterval.MINUTE);
} else {
return new TaskResultStatistics(0, 0, StatisticInterval.DAY, new Date());
}
}
/**
* Find task running statistics.
*
* @param since time span
* @return task result statistics
*/
@GET
@Path("/statistics/tasks/running")
@Consumes(MediaType.APPLICATION_JSON)
public List<TaskRunningStatistics> findTaskRunningStatistics(@QueryParam("since") final String since) {
if ("lastWeek".equals(since)) {
return statisticManager.findTaskRunningStatisticsWeekly();
} else {
return Collections.emptyList();
}
}
/**
* Get job type statistics.
*
* @return job type statistics
*/
@GET
@Path("/statistics/jobs/type")
@Consumes(MediaType.APPLICATION_JSON)
public JobTypeStatistics getJobTypeStatistics() {
return statisticManager.getJobTypeStatistics();
}
/**
* Get job execution type statistics.
*
* @return job execution statistics
*/
@GET
@Path("/statistics/jobs/executionType")
@Consumes(MediaType.APPLICATION_JSON)
public JobExecutionTypeStatistics getJobExecutionTypeStatistics() {
return statisticManager.getJobExecutionTypeStatistics();
}
/**
* Find job running statistics in the recent week.
* @param since time span
* @return collection of job running statistics in the recent week
*/
@GET
@Path("/statistics/jobs/running")
@Consumes(MediaType.APPLICATION_JSON)
public List<JobRunningStatistics> findJobRunningStatistics(@QueryParam("since") final String since) {
if ("lastWeek".equals(since)) {
return statisticManager.findJobRunningStatisticsWeekly();
} else {
return Collections.emptyList();
}
}
/**
* Find job register statistics.
*
* @return collection of job register statistics since online
*/
@GET
@Path("/statistics/jobs/register")
@Consumes(MediaType.APPLICATION_JSON)
public List<JobRegisterStatistics> findJobRegisterStatistics() {
return statisticManager.findJobRegisterStatisticsSinceOnline();
}
}
```
|
```package org.apache.shardingsphere.elasticjob.cloud.exception;
import org.hamcrest.CoreMatchers;
import org.hamcrest.core.Is;
import org.junit.Assert;
import org.junit.Test;
public final class JobSystemExceptionTest {
@Test
public void assertGetMessage() {
Assert.assertThat(new JobSystemException("message is: '%s'", "test").getMessage(), Is.is("message is: 'test'"));
}
@Test
public void assertGetCause() {
Assert.assertThat(new JobSystemException(new RuntimeException()).getCause(), CoreMatchers.instanceOf(RuntimeException.class));
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.shardingsphere.elasticjob.cloud.exception;
/**
* Job system exception.
*/
public final class JobSystemException extends RuntimeException {
private static final long serialVersionUID = 5018901344199973515L;
public JobSystemException(final String errorMessage, final Object... args) {
super(String.format(errorMessage, args));
}
public JobSystemException(final Throwable cause) {
super(cause);
}
}
```
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.mesos;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.fixture.CloudJobConfigurationBuilder;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.state.running.RunningService;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.statistics.StatisticManager;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.fixture.TaskNode;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.ha.FrameworkIDService;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.mesos.fixture.OfferBuilder;
import org.apache.shardingsphere.elasticjob.cloud.context.TaskContext;
import org.apache.shardingsphere.elasticjob.cloud.event.JobEventBus;
import org.apache.shardingsphere.elasticjob.cloud.reg.base.CoordinatorRegistryCenter;
import com.google.common.base.Optional;
import com.netflix.fenzo.TaskScheduler;
import com.netflix.fenzo.functions.Action2;
import org.apache.mesos.Protos;
import org.apache.mesos.SchedulerDriver;
import org.hamcrest.core.Is;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentMatchers;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.unitils.util.ReflectionUtils;
import java.util.Arrays;
import java.util.List;
@RunWith(MockitoJUnitRunner.class)
public final class SchedulerEngineTest {
@Mock
private TaskScheduler taskScheduler;
@Mock
private FacadeService facadeService;
@Mock
private FrameworkIDService frameworkIDService;
@Mock
private StatisticManager statisticManager;
private SchedulerEngine schedulerEngine;
@Before
public void setUp() throws NoSuchFieldException {
schedulerEngine = new SchedulerEngine(taskScheduler, facadeService, new JobEventBus(), frameworkIDService, statisticManager);
ReflectionUtils.setFieldValue(schedulerEngine, "facadeService", facadeService);
Mockito.when(facadeService.load("test_job")).thenReturn(Optional.of(CloudJobConfigurationBuilder.createCloudJobConfiguration("test_job")));
new RunningService(Mockito.mock(CoordinatorRegistryCenter.class)).clear();
}
@Test
public void assertRegistered() {
schedulerEngine.registered(null, Protos.FrameworkID.newBuilder().setValue("1").build(), Protos.MasterInfo.getDefaultInstance());
Mockito.verify(taskScheduler).expireAllLeases();
Mockito.verify(frameworkIDService).save("1");
}
@Test
public void assertReregistered() {
schedulerEngine.reregistered(null, Protos.MasterInfo.getDefaultInstance());
Mockito.verify(taskScheduler).expireAllLeases();
}
@Test
public void assertResourceOffers() {
SchedulerDriver schedulerDriver = Mockito.mock(SchedulerDriver.class);
List<Protos.Offer> offers = Arrays.asList(OfferBuilder.createOffer("offer_0"), OfferBuilder.createOffer("offer_1"));
schedulerEngine.resourceOffers(schedulerDriver, offers);
Assert.assertThat(LeasesQueue.getInstance().drainTo().size(), Is.is(2));
}
@Test
public void assertOfferRescinded() {
schedulerEngine.offerRescinded(null, Protos.OfferID.newBuilder().setValue("myOffer").build());
Mockito.verify(taskScheduler).expireLease("myOffer");
}
@Test
public void assertRunningStatusUpdateForDaemonJobBegin() {
TaskNode taskNode = TaskNode.builder().build();
schedulerEngine.statusUpdate(null, Protos.TaskStatus.newBuilder().setTaskId(Protos.TaskID.newBuilder().setValue(taskNode.getTaskNodeValue()))
.setState(Protos.TaskState.TASK_RUNNING).setMessage("BEGIN").setSlaveId(Protos.SlaveID.newBuilder().setValue("slave-S0")).build());
Mockito.verify(facadeService).updateDaemonStatus(TaskContext.from(taskNode.getTaskNodeValue()), false);
}
@Test
public void assertRunningStatusUpdateForDaemonJobComplete() {
TaskNode taskNode = TaskNode.builder().build();
schedulerEngine.statusUpdate(null, Protos.TaskStatus.newBuilder().setTaskId(Protos.TaskID.newBuilder().setValue(taskNode.getTaskNodeValue()))
.setState(Protos.TaskState.TASK_RUNNING).setMessage("COMPLETE").setSlaveId(Protos.SlaveID.newBuilder().setValue("slave-S0")).build());
Mockito.verify(facadeService).updateDaemonStatus(TaskContext.from(taskNode.getTaskNodeValue()), true);
}
@Test
public void assertRunningStatusUpdateForOther() {
TaskNode taskNode = TaskNode.builder().build();
schedulerEngine.statusUpdate(null, Protos.TaskStatus.newBuilder().setTaskId(Protos.TaskID.newBuilder().setValue(taskNode.getTaskNodeValue()))
.setState(Protos.TaskState.TASK_RUNNING).setSlaveId(Protos.SlaveID.newBuilder().setValue("slave-S0")).build());
Mockito.verify(facadeService, Mockito.times(0)).updateDaemonStatus(TaskContext.from(taskNode.getTaskNodeValue()), ArgumentMatchers.eq(ArgumentMatchers.anyBoolean()));
}
@Test
public void assertFinishedStatusUpdateWithoutLaunchedTasks() {
TaskNode taskNode = TaskNode.builder().build();
schedulerEngine.statusUpdate(null, Protos.TaskStatus.newBuilder().setTaskId(Protos.TaskID.newBuilder().setValue(taskNode.getTaskNodeValue()))
.setState(Protos.TaskState.TASK_FINISHED).setSlaveId(Protos.SlaveID.newBuilder().setValue("slave-S0")).build());
Mockito.verify(facadeService).removeRunning(TaskContext.from(taskNode.getTaskNodeValue()));
Mockito.verify(taskScheduler, Mockito.times(0)).getTaskUnAssigner();
}
@Test
public void assertFinishedStatusUpdate() {
@SuppressWarnings("unchecked")
Action2<String, String> taskUnAssigner = Mockito.mock(Action2.class);
Mockito.when(taskScheduler.getTaskUnAssigner()).thenReturn(taskUnAssigner);
TaskNode taskNode = TaskNode.builder().build();
Mockito.when(facadeService.popMapping(taskNode.getTaskNodeValue())).thenReturn("localhost");
schedulerEngine.statusUpdate(null, Protos.TaskStatus.newBuilder().setTaskId(Protos.TaskID.newBuilder().setValue(taskNode.getTaskNodeValue()))
.setState(Protos.TaskState.TASK_FINISHED).setSlaveId(Protos.SlaveID.newBuilder().setValue("slave-S0")).build());
Mockito.verify(facadeService).removeRunning(TaskContext.from(taskNode.getTaskNodeValue()));
Mockito.verify(taskUnAssigner).call(TaskContext.getIdForUnassignedSlave(taskNode.getTaskNodeValue()), "localhost");
Mockito.verify(statisticManager).taskRunSuccessfully();
}
@Test
public void assertKilledStatusUpdate() {
@SuppressWarnings("unchecked")
Action2<String, String> taskUnAssigner = Mockito.mock(Action2.class);
Mockito.when(taskScheduler.getTaskUnAssigner()).thenReturn(taskUnAssigner);
TaskNode taskNode = TaskNode.builder().build();
Mockito.when(facadeService.popMapping(taskNode.getTaskNodeValue())).thenReturn("localhost");
schedulerEngine.statusUpdate(null, Protos.TaskStatus.newBuilder().setTaskId(Protos.TaskID.newBuilder().setValue(taskNode.getTaskNodeValue()))
.setState(Protos.TaskState.TASK_KILLED).setSlaveId(Protos.SlaveID.newBuilder().setValue("slave-S0")).build());
Mockito.verify(facadeService).removeRunning(TaskContext.from(taskNode.getTaskNodeValue()));
Mockito.verify(facadeService).addDaemonJobToReadyQueue("test_job");
Mockito.verify(taskUnAssigner).call(TaskContext.getIdForUnassignedSlave(taskNode.getTaskNodeValue()), "localhost");
}
@Test
public void assertFailedStatusUpdate() {
@SuppressWarnings("unchecked")
Action2<String, String> taskUnAssigner = Mockito.mock(Action2.class);
Mockito.when(taskScheduler.getTaskUnAssigner()).thenReturn(taskUnAssigner);
TaskNode taskNode = TaskNode.builder().build();
Mockito.when(facadeService.popMapping(taskNode.getTaskNodeValue())).thenReturn("localhost");
schedulerEngine.statusUpdate(null, Protos.TaskStatus.newBuilder().setTaskId(Protos.TaskID.newBuilder().setValue(taskNode.getTaskNodeValue()))
.setState(Protos.TaskState.TASK_FAILED).setSlaveId(Protos.SlaveID.newBuilder().setValue("slave-S0")).build());
Mockito.verify(facadeService).recordFailoverTask(TaskContext.from(taskNode.getTaskNodeValue()));
Mockito.verify(facadeService).removeRunning(TaskContext.from(taskNode.getTaskNodeValue()));
Mockito.verify(taskUnAssigner).call(TaskContext.getIdForUnassignedSlave(taskNode.getTaskNodeValue()), "localhost");
Mockito.verify(statisticManager).taskRunFailed();
}
@Test
public void assertErrorStatusUpdate() {
@SuppressWarnings("unchecked")
Action2<String, String> taskUnAssigner = Mockito.mock(Action2.class);
Mockito.when(taskScheduler.getTaskUnAssigner()).thenReturn(taskUnAssigner);
TaskNode taskNode = TaskNode.builder().build();
Mockito.when(facadeService.popMapping(taskNode.getTaskNodeValue())).thenReturn("localhost");
schedulerEngine.statusUpdate(null, Protos.TaskStatus.newBuilder().setTaskId(Protos.TaskID.newBuilder().setValue(taskNode.getTaskNodeValue()))
.setState(Protos.TaskState.TASK_ERROR).setSlaveId(Protos.SlaveID.newBuilder().setValue("slave-S0")).build());
Mockito.verify(facadeService).recordFailoverTask(TaskContext.from(taskNode.getTaskNodeValue()));
Mockito.verify(facadeService).removeRunning(TaskContext.from(taskNode.getTaskNodeValue()));
Mockito.verify(taskUnAssigner).call(TaskContext.getIdForUnassignedSlave(taskNode.getTaskNodeValue()), "localhost");
Mockito.verify(statisticManager).taskRunFailed();
}
@Test
public void assertLostStatusUpdate() {
@SuppressWarnings("unchecked")
Action2<String, String> taskUnAssigner = Mockito.mock(Action2.class);
Mockito.when(taskScheduler.getTaskUnAssigner()).thenReturn(taskUnAssigner);
TaskNode taskNode = TaskNode.builder().build();
Mockito.when(facadeService.popMapping(taskNode.getTaskNodeValue())).thenReturn("localhost");
schedulerEngine.statusUpdate(null, Protos.TaskStatus.newBuilder()
.setTaskId(Protos.TaskID.newBuilder().setValue(taskNode.getTaskNodeValue())).setState(Protos.TaskState.TASK_LOST).setSlaveId(Protos.SlaveID.newBuilder().setValue("slave-S0")).build());
Mockito.verify(facadeService).recordFailoverTask(TaskContext.from(taskNode.getTaskNodeValue()));
Mockito.verify(facadeService).removeRunning(TaskContext.from(taskNode.getTaskNodeValue()));
Mockito.verify(taskUnAssigner).call(TaskContext.getIdForUnassignedSlave(taskNode.getTaskNodeValue()), "localhost");
Mockito.verify(statisticManager).taskRunFailed();
}
@Test
public void assertDroppedStatusUpdate() {
@SuppressWarnings("unchecked")
Action2<String, String> taskUnAssigner = Mockito.mock(Action2.class);
Mockito.when(taskScheduler.getTaskUnAssigner()).thenReturn(taskUnAssigner);
TaskNode taskNode = TaskNode.builder().build();
Mockito.when(facadeService.popMapping(taskNode.getTaskNodeValue())).thenReturn("localhost");
schedulerEngine.statusUpdate(null, Protos.TaskStatus.newBuilder()
.setTaskId(Protos.TaskID.newBuilder().setValue(taskNode.getTaskNodeValue())).setState(Protos.TaskState.TASK_DROPPED)
.setSlaveId(Protos.SlaveID.newBuilder().setValue("slave-S0")).build());
Mockito.verify(facadeService).recordFailoverTask(TaskContext.from(taskNode.getTaskNodeValue()));
Mockito.verify(facadeService).removeRunning(TaskContext.from(taskNode.getTaskNodeValue()));
Mockito.verify(taskUnAssigner).call(TaskContext.getIdForUnassignedSlave(taskNode.getTaskNodeValue()), "localhost");
Mockito.verify(statisticManager).taskRunFailed();
}
@Test
public void assertGoneStatusUpdate() {
@SuppressWarnings("unchecked")
Action2<String, String> taskUnAssigner = Mockito.mock(Action2.class);
Mockito.when(taskScheduler.getTaskUnAssigner()).thenReturn(taskUnAssigner);
TaskNode taskNode = TaskNode.builder().build();
Mockito.when(facadeService.popMapping(taskNode.getTaskNodeValue())).thenReturn("localhost");
schedulerEngine.statusUpdate(null, Protos.TaskStatus.newBuilder()
.setTaskId(Protos.TaskID.newBuilder().setValue(taskNode.getTaskNodeValue())).setState(Protos.TaskState.TASK_GONE).setSlaveId(Protos.SlaveID.newBuilder().setValue("slave-S0")).build());
Mockito.verify(facadeService).recordFailoverTask(TaskContext.from(taskNode.getTaskNodeValue()));
Mockito.verify(facadeService).removeRunning(TaskContext.from(taskNode.getTaskNodeValue()));
Mockito.verify(taskUnAssigner).call(TaskContext.getIdForUnassignedSlave(taskNode.getTaskNodeValue()), "localhost");
Mockito.verify(statisticManager).taskRunFailed();
}
@Test
public void assertGoneByOperatorStatusUpdate() {
@SuppressWarnings("unchecked")
Action2<String, String> taskUnAssigner = Mockito.mock(Action2.class);
Mockito.when(taskScheduler.getTaskUnAssigner()).thenReturn(taskUnAssigner);
TaskNode taskNode = TaskNode.builder().build();
Mockito.when(facadeService.popMapping(taskNode.getTaskNodeValue())).thenReturn("localhost");
schedulerEngine.statusUpdate(null, Protos.TaskStatus.newBuilder()
.setTaskId(Protos.TaskID.newBuilder().setValue(taskNode.getTaskNodeValue())).setState(Protos.TaskState.TASK_GONE_BY_OPERATOR)
.setSlaveId(Protos.SlaveID.newBuilder().setValue("slave-S0")).build());
Mockito.verify(facadeService).recordFailoverTask(TaskContext.from(taskNode.getTaskNodeValue()));
Mockito.verify(facadeService).removeRunning(TaskContext.from(taskNode.getTaskNodeValue()));
Mockito.verify(taskUnAssigner).call(TaskContext.getIdForUnassignedSlave(taskNode.getTaskNodeValue()), "localhost");
Mockito.verify(statisticManager).taskRunFailed();
}
@Test
public void assertUnknownStatusUpdate() {
TaskNode taskNode = TaskNode.builder().build();
schedulerEngine.statusUpdate(null, Protos.TaskStatus.newBuilder()
.setTaskId(Protos.TaskID.newBuilder().setValue(taskNode.getTaskNodeValue())).setState(Protos.TaskState.TASK_UNKNOWN)
.setSlaveId(Protos.SlaveID.newBuilder().setValue("slave-S0")).build());
Mockito.verify(statisticManager).taskRunFailed();
}
@Test
public void assertUnReachedStatusUpdate() {
TaskNode taskNode = TaskNode.builder().build();
schedulerEngine.statusUpdate(null, Protos.TaskStatus.newBuilder()
.setTaskId(Protos.TaskID.newBuilder().setValue(taskNode.getTaskNodeValue())).setState(Protos.TaskState.TASK_UNREACHABLE)
.setSlaveId(Protos.SlaveID.newBuilder().setValue("slave-S0")).build());
Mockito.verify(statisticManager).taskRunFailed();
}
@Test
public void assertFrameworkMessage() {
schedulerEngine.frameworkMessage(null, null, Protos.SlaveID.newBuilder().setValue("slave-S0").build(), new byte[1]);
}
@Test
public void assertSlaveLost() {
schedulerEngine.slaveLost(null, Protos.SlaveID.newBuilder().setValue("slave-S0").build());
Mockito.verify(taskScheduler).expireAllLeasesByVMId("slave-S0");
}
@Test
public void assertExecutorLost() {
schedulerEngine.executorLost(null, Protos.ExecutorID.newBuilder().setValue("test_job@-@0@-@00").build(), Protos.SlaveID.newBuilder().setValue("slave-S0").build(), 0);
}
@Test
public void assertError() {
schedulerEngine.error(null, null);
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.mesos;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.statistics.StatisticManager;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.ha.FrameworkIDService;
import org.apache.shardingsphere.elasticjob.cloud.context.TaskContext;
import org.apache.shardingsphere.elasticjob.cloud.event.JobEventBus;
import org.apache.shardingsphere.elasticjob.cloud.event.type.JobStatusTraceEvent;
import com.netflix.fenzo.TaskScheduler;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.mesos.Protos;
import org.apache.mesos.Scheduler;
import org.apache.mesos.SchedulerDriver;
import java.util.List;
/**
* Scheduler engine.
*/
@RequiredArgsConstructor
@Slf4j
public final class SchedulerEngine implements Scheduler {
private final TaskScheduler taskScheduler;
private final FacadeService facadeService;
private final JobEventBus jobEventBus;
private final FrameworkIDService frameworkIDService;
private final StatisticManager statisticManager;
@Override
public void registered(final SchedulerDriver schedulerDriver, final Protos.FrameworkID frameworkID, final Protos.MasterInfo masterInfo) {
log.info("call registered");
frameworkIDService.save(frameworkID.getValue());
taskScheduler.expireAllLeases();
MesosStateService.register(masterInfo.getHostname(), masterInfo.getPort());
}
@Override
public void reregistered(final SchedulerDriver schedulerDriver, final Protos.MasterInfo masterInfo) {
log.info("call reregistered");
taskScheduler.expireAllLeases();
MesosStateService.register(masterInfo.getHostname(), masterInfo.getPort());
}
@Override
public void resourceOffers(final SchedulerDriver schedulerDriver, final List<Protos.Offer> offers) {
for (Protos.Offer offer: offers) {
log.trace("Adding offer {} from host {}", offer.getId(), offer.getHostname());
LeasesQueue.getInstance().offer(offer);
}
}
@Override
public void offerRescinded(final SchedulerDriver schedulerDriver, final Protos.OfferID offerID) {
log.trace("call offerRescinded: {}", offerID);
taskScheduler.expireLease(offerID.getValue());
}
@Override
public void statusUpdate(final SchedulerDriver schedulerDriver, final Protos.TaskStatus taskStatus) {
String taskId = taskStatus.getTaskId().getValue();
TaskContext taskContext = TaskContext.from(taskId);
String jobName = taskContext.getMetaInfo().getJobName();
log.trace("call statusUpdate task state is: {}, task id is: {}", taskStatus.getState(), taskId);
jobEventBus.post(new JobStatusTraceEvent(jobName, taskContext.getId(), taskContext.getSlaveId(), JobStatusTraceEvent.Source.CLOUD_SCHEDULER,
taskContext.getType(), String.valueOf(taskContext.getMetaInfo().getShardingItems()), JobStatusTraceEvent.State.valueOf(taskStatus.getState().name()), taskStatus.getMessage()));
switch (taskStatus.getState()) {
case TASK_RUNNING:
if (!facadeService.load(jobName).isPresent()) {
schedulerDriver.killTask(Protos.TaskID.newBuilder().setValue(taskId).build());
}
if ("BEGIN".equals(taskStatus.getMessage())) {
facadeService.updateDaemonStatus(taskContext, false);
} else if ("COMPLETE".equals(taskStatus.getMessage())) {
facadeService.updateDaemonStatus(taskContext, true);
statisticManager.taskRunSuccessfully();
}
break;
case TASK_FINISHED:
facadeService.removeRunning(taskContext);
unAssignTask(taskId);
statisticManager.taskRunSuccessfully();
break;
case TASK_KILLED:
log.warn("task id is: {}, status is: {}, message is: {}, source is: {}", taskId, taskStatus.getState(), taskStatus.getMessage(), taskStatus.getSource());
facadeService.removeRunning(taskContext);
facadeService.addDaemonJobToReadyQueue(jobName);
unAssignTask(taskId);
break;
case TASK_LOST:
case TASK_DROPPED:
case TASK_GONE:
case TASK_GONE_BY_OPERATOR:
case TASK_FAILED:
case TASK_ERROR:
log.warn("task id is: {}, status is: {}, message is: {}, source is: {}", taskId, taskStatus.getState(), taskStatus.getMessage(), taskStatus.getSource());
facadeService.removeRunning(taskContext);
facadeService.recordFailoverTask(taskContext);
unAssignTask(taskId);
statisticManager.taskRunFailed();
break;
case TASK_UNKNOWN:
case TASK_UNREACHABLE:
log.error("task id is: {}, status is: {}, message is: {}, source is: {}", taskId, taskStatus.getState(), taskStatus.getMessage(), taskStatus.getSource());
statisticManager.taskRunFailed();
break;
default:
break;
}
}
private void unAssignTask(final String taskId) {
String hostname = facadeService.popMapping(taskId);
if (null != hostname) {
taskScheduler.getTaskUnAssigner().call(TaskContext.getIdForUnassignedSlave(taskId), hostname);
}
}
@Override
public void frameworkMessage(final SchedulerDriver schedulerDriver, final Protos.ExecutorID executorID, final Protos.SlaveID slaveID, final byte[] bytes) {
log.trace("call frameworkMessage slaveID: {}, bytes: {}", slaveID, new String(bytes));
}
@Override
public void disconnected(final SchedulerDriver schedulerDriver) {
log.warn("call disconnected");
MesosStateService.deregister();
}
@Override
public void slaveLost(final SchedulerDriver schedulerDriver, final Protos.SlaveID slaveID) {
log.warn("call slaveLost slaveID is: {}", slaveID);
taskScheduler.expireAllLeasesByVMId(slaveID.getValue());
}
@Override
public void executorLost(final SchedulerDriver schedulerDriver, final Protos.ExecutorID executorID, final Protos.SlaveID slaveID, final int i) {
log.warn("call executorLost slaveID is: {}, executorID is: {}", slaveID, executorID);
}
@Override
public void error(final SchedulerDriver schedulerDriver, final String message) {
log.error("call error, message is: {}", message);
}
}
```
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.statistics.job;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.fixture.CloudJobConfigurationBuilder;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.config.job.CloudJobConfigurationService;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.statistics.util.StatisticTimeUtils;
import org.apache.shardingsphere.elasticjob.cloud.statistics.StatisticInterval;
import org.apache.shardingsphere.elasticjob.cloud.statistics.rdb.StatisticRdbRepository;
import org.apache.shardingsphere.elasticjob.cloud.statistics.type.job.JobRegisterStatistics;
import com.google.common.base.Optional;
import com.google.common.collect.Lists;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class RegisteredJobStatisticJobTest {
@Mock
private CloudJobConfigurationService configurationService;
@Mock
private StatisticRdbRepository repository;
private RegisteredJobStatisticJob registeredJobStatisticJob;
@Before
public void setUp() {
registeredJobStatisticJob = new RegisteredJobStatisticJob();
registeredJobStatisticJob.setConfigurationService(configurationService);
registeredJobStatisticJob.setRepository(repository);
}
@Test
public void assertBuildJobDetail() {
assertThat(registeredJobStatisticJob.buildJobDetail().getKey().getName(), is(RegisteredJobStatisticJob.class.getSimpleName()));
}
@Test
public void assertBuildTrigger() throws SchedulerException {
Trigger trigger = registeredJobStatisticJob.buildTrigger();
assertThat(trigger.getKey().getName(), is(RegisteredJobStatisticJob.class.getSimpleName() + "Trigger"));
}
@Test
public void assertGetDataMap() throws SchedulerException {
assertThat((CloudJobConfigurationService) registeredJobStatisticJob.getDataMap().get("configurationService"), is(configurationService));
assertThat((StatisticRdbRepository) registeredJobStatisticJob.getDataMap().get("repository"), is(repository));
}
@Test
public void assertExecuteWhenRepositoryIsEmpty() throws SchedulerException {
Optional<JobRegisterStatistics> latestOne = Optional.absent();
when(repository.findLatestJobRegisterStatistics()).thenReturn(latestOne);
when(repository.add(any(JobRegisterStatistics.class))).thenReturn(true);
when(configurationService.loadAll()).thenReturn(Lists.newArrayList(CloudJobConfigurationBuilder.createCloudJobConfiguration("test_job")));
registeredJobStatisticJob.execute(null);
verify(repository).findLatestJobRegisterStatistics();
verify(repository).add(any(JobRegisterStatistics.class));
verify(configurationService).loadAll();
}
@Test
public void assertExecute() throws SchedulerException {
Optional<JobRegisterStatistics> latestOne = Optional.of(new JobRegisterStatistics(0, StatisticTimeUtils.getStatisticTime(StatisticInterval.DAY, -3)));
when(repository.findLatestJobRegisterStatistics()).thenReturn(latestOne);
when(repository.add(any(JobRegisterStatistics.class))).thenReturn(true);
when(configurationService.loadAll()).thenReturn(Lists.newArrayList(CloudJobConfigurationBuilder.createCloudJobConfiguration("test_job")));
registeredJobStatisticJob.execute(null);
verify(repository).findLatestJobRegisterStatistics();
verify(repository, times(3)).add(any(JobRegisterStatistics.class));
verify(configurationService).loadAll();
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.statistics.job;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.config.job.CloudJobConfigurationService;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.statistics.util.StatisticTimeUtils;
import org.apache.shardingsphere.elasticjob.cloud.statistics.StatisticInterval;
import org.apache.shardingsphere.elasticjob.cloud.statistics.rdb.StatisticRdbRepository;
import org.apache.shardingsphere.elasticjob.cloud.statistics.type.job.JobRegisterStatistics;
import com.google.common.base.Optional;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Registered job statistic.
*/
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Slf4j
public final class RegisteredJobStatisticJob extends AbstractStatisticJob {
private CloudJobConfigurationService configurationService;
private StatisticRdbRepository repository;
private final StatisticInterval execInterval = StatisticInterval.DAY;
@Override
public JobDetail buildJobDetail() {
return JobBuilder.newJob(this.getClass()).withIdentity(getJobName()).build();
}
@Override
public Trigger buildTrigger() {
return TriggerBuilder.newTrigger()
.withIdentity(getTriggerName())
.withSchedule(CronScheduleBuilder.cronSchedule(execInterval.getCron())
.withMisfireHandlingInstructionDoNothing()).build();
}
@Override
public Map<String, Object> getDataMap() {
Map<String, Object> result = new HashMap<>(2);
result.put("configurationService", configurationService);
result.put("repository", repository);
return result;
}
@Override
public void execute(final JobExecutionContext context) throws JobExecutionException {
Optional<JobRegisterStatistics> latestOne = repository.findLatestJobRegisterStatistics();
if (latestOne.isPresent()) {
fillBlankIfNeeded(latestOne.get());
}
int registeredCount = configurationService.loadAll().size();
JobRegisterStatistics jobRegisterStatistics = new JobRegisterStatistics(registeredCount, StatisticTimeUtils.getCurrentStatisticTime(execInterval));
log.debug("Add jobRegisterStatistics, registeredCount is:{}", registeredCount);
repository.add(jobRegisterStatistics);
}
private void fillBlankIfNeeded(final JobRegisterStatistics latestOne) {
List<Date> blankDateRange = findBlankStatisticTimes(latestOne.getStatisticsTime(), execInterval);
if (!blankDateRange.isEmpty()) {
log.debug("Fill blank range of jobRegisterStatistics, range is:{}", blankDateRange);
}
for (Date each : blankDateRange) {
repository.add(new JobRegisterStatistics(latestOne.getRegisteredCount(), each));
}
}
}
```
|
```package org.apache.shardingsphere.elasticjob.cloud.util.json;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import org.junit.Test;
import java.io.IOException;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
public final class GsonFactoryTest {
@Test
public void assertGetGson() {
assertThat(GsonFactory.getGson(), is(GsonFactory.getGson()));
}
@Test
public void assertRegisterTypeAdapter() {
Gson beforeRegisterGson = GsonFactory.getGson();
GsonFactory.registerTypeAdapter(GsonFactoryTest.class, new TypeAdapter() {
@Override
public Object read(final JsonReader in) throws IOException {
return null;
}
@Override
public void write(final JsonWriter out, final Object value) throws IOException {
out.jsonValue("test");
}
});
assertThat(beforeRegisterGson.toJson(new GsonFactoryTest()), is("{}"));
assertThat(GsonFactory.getGson().toJson(new GsonFactoryTest()), is("test"));
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.shardingsphere.elasticjob.cloud.util.json;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import java.lang.reflect.Type;
/**
* Gson factory.
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class GsonFactory {
private static final GsonBuilder GSON_BUILDER = new GsonBuilder();
private static volatile Gson gson = GSON_BUILDER.create();
/**
* Register type adapter.
*
* @param type Gson type
* @param typeAdapter Gson type adapter
*/
public static synchronized void registerTypeAdapter(final Type type, final TypeAdapter typeAdapter) {
GSON_BUILDER.registerTypeAdapter(type, typeAdapter);
gson = GSON_BUILDER.create();
}
/**
* Get gson instance.
*
* @return gson instance
*/
public static Gson getGson() {
return gson;
}
}
```
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.state.disable.job;
import org.apache.shardingsphere.elasticjob.cloud.reg.base.CoordinatorRegistryCenter;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public final class DisableJobServiceTest {
@Mock
private CoordinatorRegistryCenter regCenter;
private DisableJobService disableJobService;
@Before
public void setUp() throws NoSuchFieldException {
disableJobService = new DisableJobService(regCenter);
}
@Test
public void assertAdd() {
disableJobService.add("test_job");
Mockito.verify(regCenter).isExisted("/state/disable/job/test_job");
Mockito.verify(regCenter).persist("/state/disable/job/test_job", "test_job");
}
@Test
public void assertRemove() {
disableJobService.remove("test_job");
Mockito.verify(regCenter).remove("/state/disable/job/test_job");
}
@Test
public void assertIsDisabled() {
Mockito.when(regCenter.isExisted("/state/disable/job/test_job")).thenReturn(true);
Assert.assertTrue(disableJobService.isDisabled("test_job"));
Mockito.verify(regCenter).isExisted("/state/disable/job/test_job");
}
@Test
public void assertIsEnabled() {
Mockito.when(regCenter.isExisted("/state/disable/job/test_job")).thenReturn(false);
Assert.assertFalse(disableJobService.isDisabled("test_job"));
Mockito.verify(regCenter).isExisted("/state/disable/job/test_job");
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.state.disable.job;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.env.BootstrapEnvironment;
import org.apache.shardingsphere.elasticjob.cloud.reg.base.CoordinatorRegistryCenter;
import lombok.extern.slf4j.Slf4j;
/**
* Disable job service.
*/
@Slf4j
public class DisableJobService {
private final BootstrapEnvironment env = BootstrapEnvironment.getInstance();
private final CoordinatorRegistryCenter regCenter;
public DisableJobService(final CoordinatorRegistryCenter regCenter) {
this.regCenter = regCenter;
}
/**
* Add job to the disable queue.
*
* @param jobName job name
*/
public void add(final String jobName) {
if (regCenter.getNumChildren(DisableJobNode.ROOT) > env.getFrameworkConfiguration().getJobStateQueueSize()) {
log.warn("Cannot add disable job, caused by read state queue size is larger than {}.", env.getFrameworkConfiguration().getJobStateQueueSize());
return;
}
String disableJobNodePath = DisableJobNode.getDisableJobNodePath(jobName);
if (!regCenter.isExisted(disableJobNodePath)) {
regCenter.persist(disableJobNodePath, jobName);
}
}
/**
* Remove the job from the disable queue.
*
* @param jobName job name
*/
public void remove(final String jobName) {
regCenter.remove(DisableJobNode.getDisableJobNodePath(jobName));
}
/**
* Determine whether the job is in the disable queue or not.
*
* @param jobName job name
* @return true is in the disable queue, otherwise not
*/
public boolean isDisabled(final String jobName) {
return regCenter.isExisted(DisableJobNode.getDisableJobNodePath(jobName));
}
}
```
|
```package org.apache.shardingsphere.elasticjob.cloud.executor.handler;
import org.apache.shardingsphere.elasticjob.cloud.executor.handler.impl.DefaultExecutorServiceHandler;
import org.apache.shardingsphere.elasticjob.cloud.executor.handler.impl.DefaultJobExceptionHandler;
import org.apache.shardingsphere.elasticjob.cloud.fixture.APIJsonConstants;
import org.apache.shardingsphere.elasticjob.cloud.fixture.handler.IgnoreJobExceptionHandler;
import org.hamcrest.core.Is;
import org.junit.Assert;
import org.junit.Test;
import org.unitils.util.ReflectionUtils;
import java.util.Map;
public final class JobPropertiesTest {
@Test
public void assertPutInvalidKey() throws NoSuchFieldException {
JobProperties actual = new JobProperties();
actual.put("invalid_key", "");
Assert.assertTrue(getMap(actual).isEmpty());
}
@Test
public void assertPutNullValue() throws NoSuchFieldException {
JobProperties actual = new JobProperties();
actual.put(JobProperties.JobPropertiesEnum.JOB_EXCEPTION_HANDLER.getKey(), null);
Assert.assertTrue(getMap(actual).isEmpty());
}
@Test
public void assertPutSuccess() throws NoSuchFieldException {
JobProperties actual = new JobProperties();
actual.put(JobProperties.JobPropertiesEnum.JOB_EXCEPTION_HANDLER.getKey(), DefaultJobExceptionHandler.class.getCanonicalName());
Assert.assertThat(getMap(actual).size(), Is.is(1));
}
private Map getMap(final JobProperties jobProperties) throws NoSuchFieldException {
return (Map) ReflectionUtils.getFieldValue(jobProperties, JobProperties.class.getDeclaredField("map"));
}
@Test
public void assertGetWhenValueIsEmpty() throws NoSuchFieldException {
JobProperties actual = new JobProperties();
Assert.assertThat(actual.get(JobProperties.JobPropertiesEnum.JOB_EXCEPTION_HANDLER), Is.is(DefaultJobExceptionHandler.class.getCanonicalName()));
Assert.assertThat(actual.get(JobProperties.JobPropertiesEnum.EXECUTOR_SERVICE_HANDLER), Is.is(DefaultExecutorServiceHandler.class.getCanonicalName()));
}
@Test
public void assertGetWhenValueIsNotEmpty() throws NoSuchFieldException {
JobProperties actual = new JobProperties();
actual.put(JobProperties.JobPropertiesEnum.JOB_EXCEPTION_HANDLER.getKey(), IgnoreJobExceptionHandler.class.getCanonicalName());
Assert.assertThat(actual.get(JobProperties.JobPropertiesEnum.JOB_EXCEPTION_HANDLER), Is.is(IgnoreJobExceptionHandler.class.getCanonicalName()));
}
@Test
public void assertJson() {
Assert.assertThat(new JobProperties().json(), Is.is(APIJsonConstants.getJobPropertiesJson(DefaultJobExceptionHandler.class.getCanonicalName())));
}
@Test
public void assertJobPropertiesEnumFromValidValue() {
Assert.assertThat(JobProperties.JobPropertiesEnum.from(JobProperties.JobPropertiesEnum.JOB_EXCEPTION_HANDLER.getKey()), Is.is(JobProperties.JobPropertiesEnum.JOB_EXCEPTION_HANDLER));
}
@Test
public void assertJobPropertiesEnumFromInvalidValue() {
Assert.assertNull(JobProperties.JobPropertiesEnum.from("invalid"));
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.shardingsphere.elasticjob.cloud.executor.handler;
import org.apache.shardingsphere.elasticjob.cloud.executor.handler.impl.DefaultJobExceptionHandler;
import org.apache.shardingsphere.elasticjob.cloud.util.json.GsonFactory;
import org.apache.shardingsphere.elasticjob.cloud.executor.handler.impl.DefaultExecutorServiceHandler;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.RequiredArgsConstructor;
import java.util.EnumMap;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Job properties.
*/
@AllArgsConstructor
@NoArgsConstructor
public final class JobProperties {
private EnumMap<JobPropertiesEnum, String> map = new EnumMap<>(JobPropertiesEnum.class);
/**
* Put job property.
*
* @param key property key
* @param value property value
*/
public void put(final String key, final String value) {
JobPropertiesEnum jobPropertiesEnum = JobPropertiesEnum.from(key);
if (null == jobPropertiesEnum || null == value) {
return;
}
map.put(jobPropertiesEnum, value);
}
/**
* Get job property.
*
* @param jobPropertiesEnum job properties enum
* @return property value
*/
public String get(final JobPropertiesEnum jobPropertiesEnum) {
return map.containsKey(jobPropertiesEnum) ? map.get(jobPropertiesEnum) : jobPropertiesEnum.getDefaultValue();
}
/**
* Get all keys.
*
* @return all keys
*/
public String json() {
Map<String, String> jsonMap = new LinkedHashMap<>(JobPropertiesEnum.values().length, 1);
for (JobPropertiesEnum each : JobPropertiesEnum.values()) {
jsonMap.put(each.getKey(), get(each));
}
return GsonFactory.getGson().toJson(jsonMap);
}
/**
* Job properties enum.
*/
@RequiredArgsConstructor
@Getter
public enum JobPropertiesEnum {
/**
* Job execution handler.
*/
JOB_EXCEPTION_HANDLER("job_exception_handler", JobExceptionHandler.class, DefaultJobExceptionHandler.class.getCanonicalName()),
/**
* Executor service handler.
*/
EXECUTOR_SERVICE_HANDLER("executor_service_handler", ExecutorServiceHandler.class, DefaultExecutorServiceHandler.class.getCanonicalName());
private final String key;
private final Class<?> classType;
private final String defaultValue;
/**
* Get job properties enum via key.
*
* @param key property key
* @return job properties enum
*/
public static JobPropertiesEnum from(final String key) {
for (JobPropertiesEnum each : JobPropertiesEnum.values()) {
if (each.getKey().equals(key)) {
return each;
}
}
return null;
}
}
}
```
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.state.ready;
import org.hamcrest.core.Is;
import org.junit.Assert;
import org.junit.Test;
public final class ReadyNodeTest {
@Test
public void assertGetReadyJobNodePath() {
Assert.assertThat(ReadyNode.getReadyJobNodePath("test_job0000000001"), Is.is("/state/ready/test_job0000000001"));
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.state.ready;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.state.StateNode;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
/**
* Ready node.
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
final class ReadyNode {
static final String ROOT = StateNode.ROOT + "/ready";
private static final String READY_JOB = ROOT + "/%s";
static String getReadyJobNodePath(final String jobName) {
return String.format(READY_JOB, jobName);
}
}
```
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.ha;
import org.apache.shardingsphere.elasticjob.cloud.reg.base.CoordinatorRegistryCenter;
import com.google.common.base.Optional;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class FrameworkIDServiceTest {
@Mock
private CoordinatorRegistryCenter registryCenter;
private FrameworkIDService frameworkIDService;
@Before
public void init() {
MockitoAnnotations.initMocks(this);
frameworkIDService = new FrameworkIDService(registryCenter);
}
@Test
public void assertFetch() throws Exception {
when(registryCenter.getDirectly(HANode.FRAMEWORK_ID_NODE)).thenReturn("1");
Optional<String> frameworkIDOptional = frameworkIDService.fetch();
assertTrue(frameworkIDOptional.isPresent());
assertThat(frameworkIDOptional.get(), is("1"));
verify(registryCenter).getDirectly(HANode.FRAMEWORK_ID_NODE);
}
@Test
public void assertSave() throws Exception {
when(registryCenter.isExisted(HANode.FRAMEWORK_ID_NODE)).thenReturn(false);
frameworkIDService.save("1");
verify(registryCenter).isExisted(HANode.FRAMEWORK_ID_NODE);
verify(registryCenter).persist(HANode.FRAMEWORK_ID_NODE, "1");
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.ha;
import org.apache.shardingsphere.elasticjob.cloud.reg.base.CoordinatorRegistryCenter;
import com.google.common.base.Optional;
import com.google.common.base.Strings;
import lombok.RequiredArgsConstructor;
/**
* FrameworkID service.
*/
@RequiredArgsConstructor
public final class FrameworkIDService {
private final CoordinatorRegistryCenter regCenter;
/**
* Fetch FrameworkID.
*
* @return the optional value of FrameworkID
*/
public Optional<String> fetch() {
String frameworkId = regCenter.getDirectly(HANode.FRAMEWORK_ID_NODE);
return Strings.isNullOrEmpty(frameworkId) ? Optional.<String>absent() : Optional.of(frameworkId);
}
/**
* Save FrameworkID.
*
* @param id framework id
*/
public void save(final String id) {
if (!regCenter.isExisted(HANode.FRAMEWORK_ID_NODE)) {
regCenter.persist(HANode.FRAMEWORK_ID_NODE, id);
}
}
}
```
|
```package org.apache.shardingsphere.elasticjob.cloud.util.digest;
import org.hamcrest.core.Is;
import org.junit.Assert;
import org.junit.Test;
public final class EncryptionTest {
@Test
public void assertMd5() {
Assert.assertThat(Encryption.md5("test"), Is.is("98f6bcd4621d373cade4e832627b4f6"));
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.shardingsphere.elasticjob.cloud.util.digest;
import org.apache.shardingsphere.elasticjob.cloud.exception.JobSystemException;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* Encryption.
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class Encryption {
private static final String MD5 = "MD5";
/**
* Use md5 to encrypt string.
*
* @param str string to be encrypted
* @return encrypted string
*/
public static String md5(final String str) {
try {
MessageDigest messageDigest = MessageDigest.getInstance(MD5);
messageDigest.update(str.getBytes());
return new BigInteger(1, messageDigest.digest()).toString(16);
} catch (final NoSuchAlgorithmException ex) {
throw new JobSystemException(ex);
}
}
}
```
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.context;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.config.job.CloudJobConfiguration;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.fixture.CloudJobConfigurationBuilder;
import org.apache.shardingsphere.elasticjob.cloud.context.ExecutionType;
import org.hamcrest.core.Is;
import org.junit.Assert;
import org.junit.Test;
public final class JobContextTest {
@Test
public void assertFrom() {
CloudJobConfiguration jobConfig = CloudJobConfigurationBuilder.createCloudJobConfiguration("test_job");
JobContext actual = JobContext.from(jobConfig, ExecutionType.READY);
Assert.assertThat(actual.getAssignedShardingItems().size(), Is.is(10));
for (int i = 0; i < actual.getAssignedShardingItems().size(); i++) {
Assert.assertThat(actual.getAssignedShardingItems().get(i), Is.is(i));
}
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.context;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.config.job.CloudJobConfiguration;
import org.apache.shardingsphere.elasticjob.cloud.context.ExecutionType;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import java.util.ArrayList;
import java.util.List;
/**
* Job running context.
*/
@RequiredArgsConstructor
@Getter
public final class JobContext {
private final CloudJobConfiguration jobConfig;
private final List<Integer> assignedShardingItems;
private final ExecutionType type;
/**
* Create job running context from job configuration and execution type.
*
* @param jobConfig job configuration
* @param type execution type
* @return Job running context
*/
public static JobContext from(final CloudJobConfiguration jobConfig, final ExecutionType type) {
int shardingTotalCount = jobConfig.getTypeConfig().getCoreConfig().getShardingTotalCount();
List<Integer> shardingItems = new ArrayList<>(shardingTotalCount);
for (int i = 0; i < shardingTotalCount; i++) {
shardingItems.add(i);
}
return new JobContext(jobConfig, shardingItems, type);
}
}
```
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.mesos;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.restful.RestfulService;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.statistics.StatisticManager;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.env.BootstrapEnvironment;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.config.job.CloudJobConfigurationListener;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.env.FrameworkConfiguration;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.producer.ProducerManager;
import com.google.common.util.concurrent.Service;
import org.apache.mesos.SchedulerDriver;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class SchedulerServiceTest {
@Mock
private BootstrapEnvironment env;
@Mock
private CloudJobConfigurationListener cloudJobConfigurationListener;
@Mock
private FacadeService facadeService;
@Mock
private SchedulerDriver schedulerDriver;
@Mock
private ProducerManager producerManager;
@Mock
private StatisticManager statisticManager;
@Mock
private Service taskLaunchScheduledService;
@Mock
private RestfulService restfulService;
@Mock
private ReconcileService reconcileService;
private SchedulerService schedulerService;
@Before
public void setUp() throws Exception {
schedulerService = new SchedulerService(env, facadeService, schedulerDriver,
producerManager, statisticManager, cloudJobConfigurationListener,
taskLaunchScheduledService, restfulService, reconcileService);
}
@Test
public void assertStart() {
setReconcileEnabled(true);
schedulerService.start();
InOrder inOrder = getInOrder();
inOrder.verify(facadeService).start();
inOrder.verify(producerManager).startup();
inOrder.verify(statisticManager).startup();
inOrder.verify(cloudJobConfigurationListener).start();
inOrder.verify(taskLaunchScheduledService).startAsync();
inOrder.verify(restfulService).start();
inOrder.verify(schedulerDriver).start();
inOrder.verify(reconcileService).startAsync();
}
@Test
public void assertStartWithoutReconcile() {
setReconcileEnabled(false);
schedulerService.start();
InOrder inOrder = getInOrder();
inOrder.verify(facadeService).start();
inOrder.verify(producerManager).startup();
inOrder.verify(statisticManager).startup();
inOrder.verify(cloudJobConfigurationListener).start();
inOrder.verify(taskLaunchScheduledService).startAsync();
inOrder.verify(restfulService).start();
inOrder.verify(schedulerDriver).start();
inOrder.verify(reconcileService, never()).stopAsync();
}
@Test
public void assertStop() {
setReconcileEnabled(true);
schedulerService.stop();
InOrder inOrder = getInOrder();
inOrder.verify(restfulService).stop();
inOrder.verify(taskLaunchScheduledService).stopAsync();
inOrder.verify(cloudJobConfigurationListener).stop();
inOrder.verify(statisticManager).shutdown();
inOrder.verify(producerManager).shutdown();
inOrder.verify(schedulerDriver).stop(true);
inOrder.verify(facadeService).stop();
inOrder.verify(reconcileService).stopAsync();
}
@Test
public void assertStopWithoutReconcile() {
setReconcileEnabled(false);
schedulerService.stop();
InOrder inOrder = getInOrder();
inOrder.verify(restfulService).stop();
inOrder.verify(taskLaunchScheduledService).stopAsync();
inOrder.verify(cloudJobConfigurationListener).stop();
inOrder.verify(statisticManager).shutdown();
inOrder.verify(producerManager).shutdown();
inOrder.verify(schedulerDriver).stop(true);
inOrder.verify(facadeService).stop();
inOrder.verify(reconcileService, never()).stopAsync();
}
private InOrder getInOrder() {
return Mockito.inOrder(facadeService, schedulerDriver,
producerManager, statisticManager, cloudJobConfigurationListener,
taskLaunchScheduledService, restfulService, reconcileService);
}
private void setReconcileEnabled(final boolean isEnabled) {
FrameworkConfiguration frameworkConfiguration = mock(FrameworkConfiguration.class);
when(frameworkConfiguration.isEnabledReconcile()).thenReturn(isEnabled);
when(env.getFrameworkConfiguration()).thenReturn(frameworkConfiguration);
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.mesos;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.restful.RestfulService;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.statistics.StatisticManager;
import org.apache.shardingsphere.elasticjob.cloud.event.rdb.JobEventRdbConfiguration;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.config.job.CloudJobConfigurationListener;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.env.BootstrapEnvironment;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.env.MesosConfiguration;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.ha.FrameworkIDService;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.producer.ProducerManager;
import org.apache.shardingsphere.elasticjob.cloud.event.JobEventBus;
import org.apache.shardingsphere.elasticjob.cloud.reg.base.CoordinatorRegistryCenter;
import com.google.common.base.Optional;
import com.google.common.util.concurrent.Service;
import com.netflix.fenzo.TaskScheduler;
import com.netflix.fenzo.VirtualMachineLease;
import com.netflix.fenzo.functions.Action1;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.mesos.MesosSchedulerDriver;
import org.apache.mesos.Protos;
import org.apache.mesos.SchedulerDriver;
/**
* Scheduler service.
*/
@Slf4j
@AllArgsConstructor
public final class SchedulerService {
private static final String WEB_UI_PROTOCOL = "http://";
private final BootstrapEnvironment env;
private final FacadeService facadeService;
private final SchedulerDriver schedulerDriver;
private final ProducerManager producerManager;
private final StatisticManager statisticManager;
private final CloudJobConfigurationListener cloudJobConfigurationListener;
private final Service taskLaunchScheduledService;
private final RestfulService restfulService;
private final ReconcileService reconcileService;
public SchedulerService(final CoordinatorRegistryCenter regCenter) {
env = BootstrapEnvironment.getInstance();
facadeService = new FacadeService(regCenter);
statisticManager = StatisticManager.getInstance(regCenter, env.getJobEventRdbConfiguration());
TaskScheduler taskScheduler = getTaskScheduler();
JobEventBus jobEventBus = getJobEventBus();
schedulerDriver = getSchedulerDriver(taskScheduler, jobEventBus, new FrameworkIDService(regCenter));
producerManager = new ProducerManager(schedulerDriver, regCenter);
cloudJobConfigurationListener = new CloudJobConfigurationListener(regCenter, producerManager);
taskLaunchScheduledService = new TaskLaunchScheduledService(schedulerDriver, taskScheduler, facadeService, jobEventBus);
reconcileService = new ReconcileService(schedulerDriver, facadeService);
restfulService = new RestfulService(regCenter, env.getRestfulServerConfiguration(), producerManager, reconcileService);
}
private SchedulerDriver getSchedulerDriver(final TaskScheduler taskScheduler, final JobEventBus jobEventBus, final FrameworkIDService frameworkIDService) {
Optional<String> frameworkIDOptional = frameworkIDService.fetch();
Protos.FrameworkInfo.Builder builder = Protos.FrameworkInfo.newBuilder();
if (frameworkIDOptional.isPresent()) {
builder.setId(Protos.FrameworkID.newBuilder().setValue(frameworkIDOptional.get()).build());
}
Optional<String> role = env.getMesosRole();
String frameworkName = MesosConfiguration.FRAMEWORK_NAME;
if (role.isPresent()) {
builder.setRole(role.get());
frameworkName += "-" + role.get();
}
builder.addCapabilitiesBuilder().setType(Protos.FrameworkInfo.Capability.Type.PARTITION_AWARE);
MesosConfiguration mesosConfig = env.getMesosConfiguration();
Protos.FrameworkInfo frameworkInfo = builder.setUser(mesosConfig.getUser()).setName(frameworkName)
.setHostname(mesosConfig.getHostname()).setFailoverTimeout(MesosConfiguration.FRAMEWORK_FAILOVER_TIMEOUT_SECONDS)
.setWebuiUrl(WEB_UI_PROTOCOL + env.getFrameworkHostPort()).setCheckpoint(true).build();
return new MesosSchedulerDriver(new SchedulerEngine(taskScheduler, facadeService, jobEventBus, frameworkIDService, statisticManager), frameworkInfo, mesosConfig.getUrl());
}
private TaskScheduler getTaskScheduler() {
return new TaskScheduler.Builder()
.withLeaseOfferExpirySecs(1000000000L)
.withLeaseRejectAction(new Action1<VirtualMachineLease>() {
@Override
public void call(final VirtualMachineLease lease) {
log.warn("Declining offer on '{}'", lease.hostname());
schedulerDriver.declineOffer(lease.getOffer().getId());
}
}).build();
}
private JobEventBus getJobEventBus() {
Optional<JobEventRdbConfiguration> rdbConfig = env.getJobEventRdbConfiguration();
if (rdbConfig.isPresent()) {
return new JobEventBus(rdbConfig.get());
}
return new JobEventBus();
}
/**
* Start as a daemon.
*/
public void start() {
facadeService.start();
producerManager.startup();
statisticManager.startup();
cloudJobConfigurationListener.start();
taskLaunchScheduledService.startAsync();
restfulService.start();
schedulerDriver.start();
if (env.getFrameworkConfiguration().isEnabledReconcile()) {
reconcileService.startAsync();
}
}
/**
* Stop.
*/
public void stop() {
restfulService.stop();
taskLaunchScheduledService.stopAsync();
cloudJobConfigurationListener.stop();
statisticManager.shutdown();
producerManager.shutdown();
schedulerDriver.stop(true);
facadeService.stop();
if (env.getFrameworkConfiguration().isEnabledReconcile()) {
reconcileService.stopAsync();
}
}
}
```
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.statistics;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.statistics.job.StatisticJob;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.statistics.job.TestStatisticJob;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.unitils.util.ReflectionUtils;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class StatisticsSchedulerTest {
private StatisticsScheduler statisticsScheduler;
@Mock
private Scheduler scheduler;
@Before
public void setUp() throws NoSuchFieldException {
statisticsScheduler = new StatisticsScheduler();
ReflectionUtils.setFieldValue(statisticsScheduler, "scheduler", scheduler);
}
@Test
public void assertRegister() throws SchedulerException {
StatisticJob job = new TestStatisticJob();
statisticsScheduler.register(job);
verify(scheduler).scheduleJob(job.buildJobDetail(), job.buildTrigger());
}
@Test
public void assertShutdown() throws SchedulerException {
when(scheduler.isShutdown()).thenReturn(false);
statisticsScheduler.shutdown();
when(scheduler.isShutdown()).thenReturn(true);
statisticsScheduler.shutdown();
verify(scheduler).shutdown();
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.statistics;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.statistics.job.StatisticJob;
import org.apache.shardingsphere.elasticjob.cloud.exception.JobStatisticException;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.plugins.management.ShutdownHookPlugin;
import org.quartz.simpl.SimpleThreadPool;
import java.util.Properties;
/**
* Statistic scheduler.
*/
final class StatisticsScheduler {
private final StdSchedulerFactory factory;
private Scheduler scheduler;
StatisticsScheduler() {
factory = new StdSchedulerFactory();
try {
factory.initialize(getQuartzProperties());
} catch (final SchedulerException ex) {
throw new JobStatisticException(ex);
}
}
private Properties getQuartzProperties() {
Properties result = new Properties();
result.put("org.quartz.threadPool.class", SimpleThreadPool.class.getName());
result.put("org.quartz.threadPool.threadCount", Integer.toString(1));
result.put("org.quartz.scheduler.instanceName", "ELASTIC_JOB_CLOUD_STATISTICS_SCHEDULER");
result.put("org.quartz.plugin.shutdownhook.class", ShutdownHookPlugin.class.getName());
result.put("org.quartz.plugin.shutdownhook.cleanShutdown", Boolean.TRUE.toString());
return result;
}
/**
* Start.
*/
void start() {
try {
scheduler = factory.getScheduler();
scheduler.start();
} catch (final SchedulerException ex) {
throw new JobStatisticException(ex);
}
}
/**
* Register statistic job.
*
* @param statisticJob statistic job
*/
void register(final StatisticJob statisticJob) {
try {
JobDetail jobDetail = statisticJob.buildJobDetail();
jobDetail.getJobDataMap().putAll(statisticJob.getDataMap());
scheduler.scheduleJob(jobDetail, statisticJob.buildTrigger());
} catch (final SchedulerException ex) {
throw new JobStatisticException(ex);
}
}
/**
* Shutdown.
*/
void shutdown() {
try {
if (null != scheduler && !scheduler.isShutdown()) {
scheduler.shutdown();
}
} catch (final SchedulerException ex) {
throw new JobStatisticException(ex);
}
}
}
```
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.state.disable.app;
import org.hamcrest.core.Is;
import org.junit.Assert;
import org.junit.Test;
public final class DisableAppNodeTest {
@Test
public void assertGetDisableAppNodePath() {
Assert.assertThat(DisableAppNode.getDisableAppNodePath("test_app0000000001"), Is.is("/state/disable/app/test_app0000000001"));
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.state.disable.app;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.state.StateNode;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
/**
* Disable app node.
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
final class DisableAppNode {
static final String ROOT = StateNode.ROOT + "/disable/app";
private static final String DISABLE_APP = ROOT + "/%s";
static String getDisableAppNodePath(final String appName) {
return String.format(DISABLE_APP, appName);
}
}
```
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.restful;
import com.google.common.collect.Lists;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.fixture.CloudAppJsonConstants;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.fixture.CloudJsonConstants;
import org.hamcrest.core.Is;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public final class CloudAppRestfulApiTest extends AbstractCloudRestfulApiTest {
@Test
public void assertRegister() throws Exception {
Mockito.when(getRegCenter().isExisted("/config/app/test_app")).thenReturn(false);
Assert.assertThat(RestfulTestsUtil.sentRequest("http://127.0.0.1:19000/api/app", "POST", CloudAppJsonConstants.getAppJson("test_app")), Is.is(204));
Mockito.verify(getRegCenter()).persist("/config/app/test_app", CloudAppJsonConstants.getAppJson("test_app"));
}
@Test
public void assertRegisterWithExistedName() throws Exception {
Mockito.when(getRegCenter().isExisted("/config/app/test_app")).thenReturn(false);
Assert.assertThat(RestfulTestsUtil.sentRequest("http://127.0.0.1:19000/api/app", "POST", CloudAppJsonConstants.getAppJson("test_app")), Is.is(204));
Mockito.when(getRegCenter().get("/config/app/test_app")).thenReturn(CloudAppJsonConstants.getAppJson("test_app"));
Assert.assertThat(RestfulTestsUtil.sentRequest("http://127.0.0.1:19000/api/app", "POST", CloudAppJsonConstants.getAppJson("test_app")), Is.is(500));
}
@Test
public void assertRegisterWithBadRequest() throws Exception {
Assert.assertThat(RestfulTestsUtil.sentRequest("http://127.0.0.1:19000/api/app", "POST", "\"{\"appName\":\"wrong_job\"}"), Is.is(500));
}
@Test
public void assertUpdate() throws Exception {
Mockito.when(getRegCenter().isExisted("/config/app/test_app")).thenReturn(true);
Mockito.when(getRegCenter().get("/config/app/test_app")).thenReturn(CloudAppJsonConstants.getAppJson("test_app"));
Assert.assertThat(RestfulTestsUtil.sentRequest("http://127.0.0.1:19000/api/app", "PUT", CloudAppJsonConstants.getAppJson("test_app")), Is.is(204));
Mockito.verify(getRegCenter()).update("/config/app/test_app", CloudAppJsonConstants.getAppJson("test_app"));
}
@Test
public void assertDetail() throws Exception {
Mockito.when(getRegCenter().get("/config/app/test_app")).thenReturn(CloudAppJsonConstants.getAppJson("test_app"));
Assert.assertThat(RestfulTestsUtil.sentGetRequest("http://127.0.0.1:19000/api/app/test_app"), Is.is(CloudAppJsonConstants.getAppJson("test_app")));
Mockito.verify(getRegCenter()).get("/config/app/test_app");
}
@Test
public void assertDetailWithNotExistedJob() throws Exception {
Assert.assertThat(RestfulTestsUtil.sentRequest("http://127.0.0.1:19000/api/app/notExistedJobName", "GET", ""), Is.is(404));
}
@Test
public void assertFindAllJobs() throws Exception {
Mockito.when(getRegCenter().isExisted("/config/app")).thenReturn(true);
Mockito.when(getRegCenter().getChildrenKeys("/config/app")).thenReturn(Lists.newArrayList("test_app"));
Mockito.when(getRegCenter().get("/config/app/test_app")).thenReturn(CloudAppJsonConstants.getAppJson("test_app"));
Assert.assertThat(RestfulTestsUtil.sentGetRequest("http://127.0.0.1:19000/api/app/list"), Is.is("[" + CloudAppJsonConstants.getAppJson("test_app") + "]"));
Mockito.verify(getRegCenter()).isExisted("/config/app");
Mockito.verify(getRegCenter()).getChildrenKeys("/config/app");
Mockito.verify(getRegCenter()).get("/config/app/test_app");
}
@Test
public void assertDeregister() throws Exception {
Mockito.when(getRegCenter().get("/config/app/test_app")).thenReturn(CloudAppJsonConstants.getAppJson("test_app"));
Assert.assertThat(RestfulTestsUtil.sentRequest("http://127.0.0.1:19000/api/app/test_app", "DELETE", CloudAppJsonConstants.getAppJson("test_app")), Is.is(204));
Mockito.verify(getRegCenter()).get("/config/app/test_app");
}
@Test
public void assertIsDisabled() throws Exception {
Mockito.when(getRegCenter().isExisted("/state/disable/app/test_app")).thenReturn(true);
Assert.assertThat(RestfulTestsUtil.sentGetRequest("http://127.0.0.1:19000/api/app/test_app/disable"), Is.is("true"));
}
@Test
public void assertDisable() throws Exception {
Mockito.when(getRegCenter().isExisted("/config/job")).thenReturn(true);
Mockito.when(getRegCenter().getChildrenKeys("/config/job")).thenReturn(Lists.newArrayList("test_job"));
Mockito.when(getRegCenter().get("/config/app/test_app")).thenReturn(CloudAppJsonConstants.getAppJson("test_app"));
Mockito.when(getRegCenter().get("/config/job/test_job")).thenReturn(CloudJsonConstants.getJobJson());
Assert.assertThat(RestfulTestsUtil.sentRequest("http://127.0.0.1:19000/api/app/test_app/disable", "POST"), Is.is(204));
Mockito.verify(getRegCenter()).get("/config/app/test_app");
Mockito.verify(getRegCenter()).persist("/state/disable/app/test_app", "test_app");
}
@Test
public void assertEnable() throws Exception {
Mockito.when(getRegCenter().isExisted("/config/job")).thenReturn(true);
Mockito.when(getRegCenter().getChildrenKeys("/config/job")).thenReturn(Lists.newArrayList("test_job"));
Mockito.when(getRegCenter().get("/config/app/test_app")).thenReturn(CloudAppJsonConstants.getAppJson("test_app"));
Mockito.when(getRegCenter().get("/config/job/test_job")).thenReturn(CloudJsonConstants.getJobJson());
Assert.assertThat(RestfulTestsUtil.sentRequest("http://127.0.0.1:19000/api/app/test_app/enable", "POST"), Is.is(204));
Mockito.verify(getRegCenter()).get("/config/app/test_app");
Mockito.verify(getRegCenter()).remove("/state/disable/app/test_app");
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.restful;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.config.app.CloudAppConfigurationGsonFactory;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.mesos.MesosStateService;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.state.disable.app.DisableAppService;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.config.app.CloudAppConfiguration;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.config.app.CloudAppConfigurationService;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.config.job.CloudJobConfiguration;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.config.job.CloudJobConfigurationService;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.producer.ProducerManager;
import org.apache.shardingsphere.elasticjob.cloud.exception.AppConfigurationException;
import org.apache.shardingsphere.elasticjob.cloud.exception.JobSystemException;
import org.apache.shardingsphere.elasticjob.cloud.reg.base.CoordinatorRegistryCenter;
import org.apache.shardingsphere.elasticjob.cloud.util.json.GsonFactory;
import com.google.common.base.Optional;
import org.apache.mesos.Protos.ExecutorID;
import org.apache.mesos.Protos.SlaveID;
import org.codehaus.jettison.json.JSONException;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.Collection;
/**
* Cloud app restful api.
*/
@Path("/app")
public final class CloudAppRestfulApi {
private static CoordinatorRegistryCenter regCenter;
private static ProducerManager producerManager;
private final CloudAppConfigurationService appConfigService;
private final CloudJobConfigurationService jobConfigService;
private final DisableAppService disableAppService;
private final MesosStateService mesosStateService;
public CloudAppRestfulApi() {
appConfigService = new CloudAppConfigurationService(regCenter);
jobConfigService = new CloudJobConfigurationService(regCenter);
mesosStateService = new MesosStateService(regCenter);
disableAppService = new DisableAppService(regCenter);
}
/**
* Init.
*
* @param producerManager producer manager
* @param regCenter registry center
*/
public static void init(final CoordinatorRegistryCenter regCenter, final ProducerManager producerManager) {
CloudAppRestfulApi.regCenter = regCenter;
CloudAppRestfulApi.producerManager = producerManager;
GsonFactory.registerTypeAdapter(CloudAppConfiguration.class, new CloudAppConfigurationGsonFactory.CloudAppConfigurationGsonTypeAdapter());
}
/**
* Register app config.
*
* @param appConfig cloud app config
*/
@POST
@Consumes(MediaType.APPLICATION_JSON)
public void register(final CloudAppConfiguration appConfig) {
Optional<CloudAppConfiguration> appConfigFromZk = appConfigService.load(appConfig.getAppName());
if (appConfigFromZk.isPresent()) {
throw new AppConfigurationException("app '%s' already existed.", appConfig.getAppName());
}
appConfigService.add(appConfig);
}
/**
* Update app config.
*
* @param appConfig cloud app config
*/
@PUT
@Consumes(MediaType.APPLICATION_JSON)
public void update(final CloudAppConfiguration appConfig) {
appConfigService.update(appConfig);
}
/**
* Query app config.
*
* @param appName app name
* @return cloud app config
*/
@GET
@Path("/{appName}")
@Consumes(MediaType.APPLICATION_JSON)
public Response detail(@PathParam("appName") final String appName) {
Optional<CloudAppConfiguration> appConfig = appConfigService.load(appName);
if (!appConfig.isPresent()) {
return Response.status(Response.Status.NOT_FOUND).build();
}
return Response.ok(appConfig.get()).build();
}
/**
* Find all registered app configs.
*
* @return collection of registered app configs
*/
@GET
@Path("/list")
@Produces(MediaType.APPLICATION_JSON)
public Collection<CloudAppConfiguration> findAllApps() {
return appConfigService.loadAll();
}
/**
* Query the app is disabled or not.
*
* @param appName app name
* @return true is disabled, otherwise not
* @throws JSONException parse json exception
*/
@GET
@Path("/{appName}/disable")
@Produces(MediaType.APPLICATION_JSON)
public boolean isDisabled(@PathParam("appName") final String appName) throws JSONException {
return disableAppService.isDisabled(appName);
}
/**
* Disable app config.
*
* @param appName app name
*/
@POST
@Path("/{appName}/disable")
public void disable(@PathParam("appName") final String appName) {
if (appConfigService.load(appName).isPresent()) {
disableAppService.add(appName);
for (CloudJobConfiguration each : jobConfigService.loadAll()) {
if (appName.equals(each.getAppName())) {
producerManager.unschedule(each.getJobName());
}
}
}
}
/**
* Enable app.
*
* @param appName app name
* @throws JSONException parse json exception
*/
@POST
@Path("/{appName}/enable")
public void enable(@PathParam("appName") final String appName) throws JSONException {
if (appConfigService.load(appName).isPresent()) {
disableAppService.remove(appName);
for (CloudJobConfiguration each : jobConfigService.loadAll()) {
if (appName.equals(each.getAppName())) {
producerManager.reschedule(each.getJobName());
}
}
}
}
/**
* Deregister app.
*
* @param appName app name
*/
@DELETE
@Path("/{appName}")
@Consumes(MediaType.APPLICATION_JSON)
public void deregister(@PathParam("appName") final String appName) {
if (appConfigService.load(appName).isPresent()) {
removeAppAndJobConfigurations(appName);
stopExecutors(appName);
}
}
private void removeAppAndJobConfigurations(final String appName) {
for (CloudJobConfiguration each : jobConfigService.loadAll()) {
if (appName.equals(each.getAppName())) {
producerManager.deregister(each.getJobName());
}
}
disableAppService.remove(appName);
appConfigService.remove(appName);
}
private void stopExecutors(final String appName) {
try {
Collection<MesosStateService.ExecutorStateInfo> executorBriefInfo = mesosStateService.executors(appName);
for (MesosStateService.ExecutorStateInfo each : executorBriefInfo) {
producerManager.sendFrameworkMessage(ExecutorID.newBuilder().setValue(each.getId()).build(),
SlaveID.newBuilder().setValue(each.getSlaveId()).build(), "STOP".getBytes());
}
} catch (final JSONException ex) {
throw new JobSystemException(ex);
}
}
}
```
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.fixture;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.config.app.CloudAppConfiguration;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class CloudAppConfigurationBuilder {
/**
* Create cloud app configuration.
* @param appName app name
* @return CloudAppConfiguration
*/
public static CloudAppConfiguration createCloudAppConfiguration(final String appName) {
return new CloudAppConfiguration(appName, "http://localhost/app.jar", "bin/start.sh");
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.shardingsphere.elasticjob.cloud.scheduler.config.app;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.ToString;
/**
* Cloud app configuration.
*/
@AllArgsConstructor
@RequiredArgsConstructor
@Getter
@ToString
public final class CloudAppConfiguration {
private final String appName;
private final String appURL;
private final String bootstrapScript;
private double cpuCount = 1;
private double memoryMB = 128;
private boolean appCacheEnable = true;
private int eventTraceSamplingCount;
}
```
|
```package io.vertx.ext.auth;
import io.vertx.core.http.HttpClient;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.HttpServer;
import io.vertx.ext.auth.authorization.AuthorizationContext;
import io.vertx.ext.auth.authorization.RoleBasedAuthorization;
import io.vertx.ext.auth.authorization.impl.AuthorizationContextImpl;
import io.vertx.ext.auth.authorization.impl.RoleBasedAuthorizationConverter;
import io.vertx.ext.unit.Async;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.RunTestOnContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.Collections;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
@RunWith(VertxUnitRunner.class)
public class RoleBasedAuthorizationTest {
@Rule
public final RunTestOnContext rule = new RunTestOnContext();
@Test
public void testConverter() {
TestUtils.testJsonCodec(RoleBasedAuthorization.create("role1"), RoleBasedAuthorizationConverter::encode,
RoleBasedAuthorizationConverter::decode);
TestUtils.testJsonCodec(RoleBasedAuthorization.create("role1").setResource("resource"),
RoleBasedAuthorizationConverter::encode, RoleBasedAuthorizationConverter::decode);
}
@Test
public void testImplies1() {
assertTrue(RoleBasedAuthorization.create("role1").verify(RoleBasedAuthorization.create("role1")));
}
@Test
public void testImplies2() {
assertTrue(RoleBasedAuthorization.create("p1").setResource("r1")
.verify(RoleBasedAuthorization.create("p1").setResource("r1")));
}
@Test
public void testImplies3() {
assertFalse(RoleBasedAuthorization.create("p1").setResource("r1").verify(RoleBasedAuthorization.create("p1")));
}
@Test
public void testImplies4() {
assertFalse(RoleBasedAuthorization.create("p1").verify(RoleBasedAuthorization.create("p1").setResource("r1")));
}
@Test
public void testImplies5() {
assertFalse(RoleBasedAuthorization.create("role1").verify(RoleBasedAuthorization.create("role2")));
}
@Test
public void testMatch1(TestContext should) {
Async test = should.async();
HttpClient client = rule.vertx().createHttpClient();
final HttpServer server = rule.vertx().createHttpServer();
server.requestHandler(request -> {
User user = User.fromName("dummy user");
user.authorizations().put("providerId", Collections.singleton(RoleBasedAuthorization.create("p1").setResource("r1")));
AuthorizationContext context = new AuthorizationContextImpl(user, request.params());
should.assertTrue(RoleBasedAuthorization.create("p1").setResource("{variable1}").match(context));
request.response().end();
}).listen(0, "localhost").onComplete(should.asyncAssertSuccess(s -> {
client.request(HttpMethod.GET, s.actualPort(), "localhost", "/?variable1=r1").onComplete(should.asyncAssertSuccess(req -> {
req.send().onComplete(should.asyncAssertSuccess(res -> {
server.close().onComplete(close -> test.complete());
}));
}));
}));
}
@Test
public void testMatch2(TestContext should) {
Async test = should.async();
HttpServer server = rule.vertx().createHttpServer();
HttpClient client = rule.vertx().createHttpClient();
server.requestHandler(request -> {
User user = User.fromName("dummy user");
user.authorizations().put("providerId", Collections.singleton(RoleBasedAuthorization.create("p1").setResource("r1")));
AuthorizationContext context = new AuthorizationContextImpl(user, request.params());
should.assertFalse(RoleBasedAuthorization.create("p1").setResource("{variable1}").match(context));
request.response().end();
}).listen(0, "localhost").onComplete(should.asyncAssertSuccess(s -> {
client.request(HttpMethod.GET, s.actualPort(), "localhost", "/?variable1=r2").onComplete(should.asyncAssertSuccess(req -> {
req.send().onComplete(should.asyncAssertSuccess(res -> {
server.close().onComplete(close -> test.complete());
}));
}));
}));
}
}
```
|
Please help me generate a test for this class.
|
```package io.vertx.ext.auth.authorization;
import io.vertx.codegen.annotations.Fluent;
import io.vertx.codegen.annotations.VertxGen;
import io.vertx.ext.auth.authorization.impl.RoleBasedAuthorizationImpl;
/**
* Represents a role. Note that this role can optionally be assigned to a
* specific resource
*
* @author <a href="mail://stephane.bastian.dev@gmail.com">Stephane Bastian</a>
*/
@VertxGen
public interface RoleBasedAuthorization extends Authorization {
static RoleBasedAuthorization create(String role) {
return new RoleBasedAuthorizationImpl(role);
}
/**
* returns the role
*
* @return
*/
String getRole();
/**
* returns an optional resource that the role is assigned-on
*
* @return
*/
String getResource();
/**
* sets an optional resource that the role is assigned-on
*
* @return
*/
@Fluent
RoleBasedAuthorization setResource(String resource);
}
```
|
```package io.vertx.ext.auth.impl;
import io.vertx.core.json.JsonObject;
import org.junit.Test;
import static org.junit.Assert.*;
public class UserConverterTest {
@Test
public void encode_UserImpl_defaultCtor() {
JsonObject json = UserConverter.encode(new UserImpl());
assertNull(json.getValue("principal"));
assertFalse(json.containsKey("authorizations"));
assertNull(json.getValue("attributes"));
}
}
```
|
Please help me generate a test for this class.
|
```package io.vertx.ext.auth.impl;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.auth.User;
import io.vertx.ext.auth.authorization.Authorization;
import io.vertx.ext.auth.authorization.Authorizations;
import io.vertx.ext.auth.authorization.impl.AuthorizationConverter;
import java.util.*;
public class UserConverter {
private final static String FIELD_PRINCIPAL = "principal";
private final static String FIELD_AUTHORIZATIONS = "authorizations";
private final static String FIELD_ATTRIBUTES = "attributes";
public static JsonObject encode(User value) throws IllegalArgumentException {
Objects.requireNonNull(value);
JsonObject json = new JsonObject();
json.put(FIELD_PRINCIPAL, value.principal());
Authorizations authorizations = value.authorizations();
if (authorizations != null && !authorizations.isEmpty()) {
JsonObject jsonAuthorizations = new JsonObject();
authorizations
.forEach((providerId, authorization) -> {
final JsonArray jsonAuthorizationByProvider;
if (jsonAuthorizations.containsKey(providerId)) {
jsonAuthorizationByProvider = jsonAuthorizations.getJsonArray(providerId);
} else {
jsonAuthorizationByProvider = new JsonArray();
jsonAuthorizations.put(providerId, jsonAuthorizationByProvider);
}
jsonAuthorizationByProvider.add(AuthorizationConverter.encode(authorization));
});
json.put(FIELD_AUTHORIZATIONS, jsonAuthorizations);
}
json.put(FIELD_ATTRIBUTES, value.attributes());
return json;
}
public static User decode(JsonObject json) throws IllegalArgumentException {
Objects.requireNonNull(json);
JsonObject principal = json.getJsonObject(FIELD_PRINCIPAL);
User user = User.create(principal);
// authorizations
JsonObject jsonAuthorizations = json.getJsonObject(FIELD_AUTHORIZATIONS);
final Map<String, Set<Authorization>> decodedAuthorizations;
if (jsonAuthorizations != null) {
decodedAuthorizations = new HashMap<>(jsonAuthorizations.size());
for (String fieldName : jsonAuthorizations.fieldNames()) {
JsonArray jsonAuthorizationByProvider = jsonAuthorizations.getJsonArray(fieldName);
final Set<Authorization> authorizations;
if (jsonAuthorizationByProvider == null) {
authorizations = Collections.emptySet();
} else {
authorizations = new HashSet<>(jsonAuthorizationByProvider.size());
for (int i = 0; i < jsonAuthorizationByProvider.size(); i++) {
authorizations.add(AuthorizationConverter.decode(jsonAuthorizationByProvider.getJsonObject(i)));
}
}
decodedAuthorizations.put(fieldName, authorizations);
}
user.authorizations()
.putAll(decodedAuthorizations);
}
user.attributes()
.mergeIn(json.getJsonObject(FIELD_ATTRIBUTES, new JsonObject()));
return user;
}
}
```
|
```package io.vertx.ext.auth.test.jwt;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.auth.User;
import io.vertx.ext.auth.authorization.RoleBasedAuthorization;
import io.vertx.ext.auth.jwt.authorization.MicroProfileAuthorization;
import io.vertx.ext.unit.Async;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.RunTestOnContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.Arrays;
import java.util.List;
@RunWith(VertxUnitRunner.class)
public class MicroProfileTest {
@Rule
public RunTestOnContext rule = new RunTestOnContext();
@Test
public void itShouldAssertThatTokenHasRoles(TestContext should) {
final Async test = should.async();
User user = User.create(
new JsonObject().put("access_token", "jwt"),
new JsonObject()
.put("accessToken",
new JsonObject(
"{\n" +
" \"iss\": \"https://server.example.com\",\n" +
" \"aud\": \"s6BhdRkqt3\",\n" +
" \"jti\": \"a-123\",\n" +
" \"exp\": 999999999999,\n" +
" \"iat\": 1311280970,\n" +
" \"sub\": \"24400320\",\n" +
" \"upn\": \"jdoe@server.example.com\",\n" +
" \"groups\": [\"red-group\", \"green-group\", \"admin-group\", \"admin\"]\n" +
"}")));
// assert that the user has the following roles:
final List<String> roles = Arrays.asList("red-group", "green-group", "admin-group", "admin");
MicroProfileAuthorization.create().getAuthorizations(user)
.onComplete(call -> {
should.assertTrue(call.succeeded());
for (String role : roles) {
should.assertTrue(RoleBasedAuthorization.create(role).match(user));
}
test.complete();
});
}
@Test
public void itShouldNotFailForMissingGroupsField(TestContext should) {
final Async test = should.async();
User user = User.create(
new JsonObject().put("access_token", "jwt"),
new JsonObject().put("accessToken",
new JsonObject(
"{\n" +
" \"iss\": \"https://server.example.com\",\n" +
" \"aud\": \"s6BhdRkqt3\",\n" +
" \"jti\": \"a-123\",\n" +
" \"exp\": 999999999999,\n" +
" \"iat\": 1311280970,\n" +
" \"sub\": \"24400320\"\n" +
"}")));
MicroProfileAuthorization.create().getAuthorizations(user)
.onComplete(call -> {
should.assertTrue(call.succeeded());
test.complete();
});
}
@Test
public void itShouldBeFalseForRoleUnknown(TestContext should) {
final Async test = should.async();
User user = User.create(
new JsonObject().put("access_token", "jwt"),
new JsonObject().put("accessToken",
new JsonObject(
"{\n" +
" \"iss\": \"https://server.example.com\",\n" +
" \"aud\": \"s6BhdRkqt3\",\n" +
" \"jti\": \"a-123\",\n" +
" \"exp\": 999999999999,\n" +
" \"iat\": 1311280970,\n" +
" \"sub\": \"24400320\",\n" +
" \"upn\": \"jdoe@server.example.com\",\n" +
" \"groups\": [\"red-group\", \"green-group\", \"admin-group\", \"admin\"]\n" +
"}")));
MicroProfileAuthorization.create().getAuthorizations(user)
.onComplete(call -> {
should.assertTrue(call.succeeded());
should.assertFalse(user.authorizations().isEmpty());
should.assertFalse(RoleBasedAuthorization.create("unknown").match(user));
test.complete();
});
}
}
```
|
Please help me generate a test for this class.
|
```package io.vertx.ext.auth.jwt.authorization;
import io.vertx.codegen.annotations.VertxGen;
import io.vertx.ext.auth.User;
import io.vertx.ext.auth.authorization.AuthorizationProvider;
import io.vertx.ext.auth.jwt.authorization.impl.MicroProfileAuthorizationImpl;
/**
* Implementation of the Microprofile MP-JWT 1.1 RBAC based on the access token groups key.
*
* @author <a href="mailto:plopes@redhat.com">Paulo Lopes</a>.
*/
@VertxGen
public interface MicroProfileAuthorization extends AuthorizationProvider {
/**
* Factory method to create a Authorization provider for tokens adhering to the MP-JWT 1.1 spec.
* When the user is known to not be a JWT, (e.g.: a OAuth2 response token) then the root claim
* is expected to be extracted from {@link User#attributes()} under the key {@code accessToken}.
*
* @return a AuthorizationProvider
*/
static MicroProfileAuthorization create() {
return new MicroProfileAuthorizationImpl();
}
}
```
|
```package io.vertx.ext.auth.abac;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.auth.User;
import io.vertx.ext.auth.abac.Policy;
import io.vertx.ext.unit.junit.RunTestOnContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
@RunWith(VertxUnitRunner.class)
public class PolicyTest {
@Rule
public final RunTestOnContext rule = new RunTestOnContext();
@Test
public void createPolicy() {
Policy policy = new Policy();
policy.addAttribute(Attribute.has("/principal/amr","mfa"));
assertEquals(1, policy.getAttributes().size());
User paulo = User.fromName("paulo");
paulo.principal().put("amr", new JsonArray().add("mfa").add("pwd"));
for (Attribute attribute : policy.getAttributes()) {
assertTrue(attribute.match(paulo));
}
}
@Test
public void testReadPolicyWithAttributes() {
JsonObject json = new JsonObject(
"{\n" +
" \"name\" : \"EU users\",\n" +
" \"attributes\" : {\n" +
" \"/attributes/location\" : {\n" +
" \"eq\" : \"EU\"\n" +
" }\n" +
" },\n" +
" \"authorizations\" : [ {\n" +
" \"type\" : \"wildcard\",\n" +
" \"permission\" : \"web:GET\",\n" +
" \"resource\" : \"/gdpr\"\n" +
" } ]\n" +
"}"
);
Policy policy = new Policy(json);
assertEquals(1, policy.getAttributes().size());
for (Attribute attribute : policy.getAttributes()) {
User user = User.fromName("paulo");
user.attributes().put("location", "EU");
assertTrue(attribute.match(user));
}
}
}
```
|
Please help me generate a test for this class.
|
```package io.vertx.ext.auth.abac;
import io.vertx.codegen.annotations.DataObject;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.auth.User;
import io.vertx.ext.auth.abac.impl.AttributeImpl;
import io.vertx.ext.auth.authorization.AndAuthorization;
import io.vertx.ext.auth.authorization.Authorization;
import io.vertx.ext.auth.authorization.OrAuthorization;
import io.vertx.ext.auth.authorization.impl.AuthorizationConverter;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
/**
* Simple definition of ABAC policies. A policy is a set of rules that are evaluated against a set of attributes.
* On successful evaluation the policy is considered to be satisfied and the listed authorizations are granted.
*/
@DataObject
public class Policy {
private String name;
private Set<String> subjects;
private Set<Attribute> attributes;
private Set<Authorization> authorizations;
public Policy() {
}
public Policy(JsonObject json) {
name = json.getString("name");
if (json.containsKey("subjects")) {
subjects = json
.getJsonArray("subjects")
.stream()
.map(String.class::cast)
.collect(Collectors.toSet());
}
if (json.containsKey("attributes")) {
attributes = json
.getJsonObject("attributes")
.stream()
.map(kv -> new AttributeImpl(kv.getKey(), (JsonObject) kv.getValue()))
.collect(Collectors.toSet());
}
if (json.containsKey("authorizations")) {
authorizations = json
.getJsonArray("authorizations")
.stream()
.map(JsonObject.class::cast)
.map(AuthorizationConverter::decode)
.peek(authn -> {
if (authn instanceof AndAuthorization || authn instanceof OrAuthorization) {
throw new IllegalArgumentException("AND/OR Authorizations are not allowed in a policy");
}
})
.collect(Collectors.toSet());
}
}
/**
* Get the name of the policy
*/
public String getName() {
return name;
}
/**
* Set the policy name. This is optional and has no effect on the policy evaluation.
*
* @param name the name.
*/
public Policy setName(String name) {
this.name = name;
return this;
}
/**
* Get the subjects of the policy. This is an exact match on subject ids.
*/
public Set<String> getSubjects() {
return subjects;
}
/**
* Add a subject to the current policy.
*
* @param subject the subject id as in the return of {@link User#subject()}
*/
public Policy addSubject(String subject) {
if (subjects == null) {
subjects = new HashSet<>();
}
subjects.add(subject);
return this;
}
/**
* Replaces all active subjects with the given set. No {@code subjects} implies that the policy applies to all users.
*/
public Policy setSubjects(Set<String> subjects) {
this.subjects = subjects;
return this;
}
/**
* Get the attributes of the policy. Attributes are environmental values that are extracted from the {@link User}.
* Attributes are used to filter the amount of policies to be evaluated. For example, if a policy has an attribute:
*
* <pre>{/principal/amr: {"in: ["pwd"]}}</pre>
* <p>
* It will filter out any user that wasn't authenticated with a {@code username/password}.
*/
public Set<Attribute> getAttributes() {
return attributes;
}
/**
* Set the attributes of the policy. Attributes are environmental values that are extracted from the {@link User}.
*/
public Policy setAttributes(Set<Attribute> attributes) {
this.attributes = attributes;
return this;
}
/**
* Add an attribute to the policy.
*/
public Policy addAttribute(Attribute attribute) {
Objects.requireNonNull(attribute, "attribute cannot be null");
if (attributes == null) {
attributes = new HashSet<>();
}
attributes.add(attribute);
return this;
}
/**
* Get the authorizations of the policy. Authorizations are the actual permissions that are granted to the user.
* If a user matches the policy (meaning the subjects and attributes match) then the authorizations applied to the
* user so they can be later evaluated.
*/
public Set<Authorization> getAuthorizations() {
return authorizations;
}
/**
* Set the authorizations of the policy. Authorizations are the actual permissions that are granted to the user.
* Composite authorizations ({@link AndAuthorization} and {@link OrAuthorization}) are not allowed in a policy.
*/
public Policy setAuthorizations(Set<Authorization> authorizations) {
if (authorizations != null) {
authorizations
.forEach(authn -> {
if (authn instanceof AndAuthorization || authn instanceof OrAuthorization) {
throw new IllegalArgumentException("AND/OR Authorizations are not allowed in a policy");
}
});
}
this.authorizations = authorizations;
return this;
}
/**
* Add an authorization to the policy. Composite authorizations ({@link AndAuthorization} and
* {@link OrAuthorization}) are not allowed in a policy.
*/
public Policy addAuthorization(Authorization authorization) {
Objects.requireNonNull(authorization, "authorization cannot be null");
if (authorization instanceof AndAuthorization || authorization instanceof OrAuthorization) {
throw new IllegalArgumentException("AND/OR Authorizations are not allowed in a policy");
}
if (authorizations == null) {
authorizations = new HashSet<>();
}
authorizations.add(authorization);
return this;
}
/**
* Encode this policy as a JSON document to facilitate storage and retrieval.
*/
public JsonObject toJson() {
final JsonObject json = new JsonObject();
if (name != null) {
json.put("name", name);
}
if (subjects != null) {
JsonArray array = new JsonArray();
subjects.forEach(array::add);
json.put("subjects", array);
}
if (attributes != null) {
JsonObject object = new JsonObject();
attributes.forEach(el -> object.mergeIn(el.toJson()));
json.put("attributes", object);
}
if (authorizations != null) {
JsonArray array = new JsonArray();
authorizations.forEach(el -> array.add(el.toJson()));
json.put("authorizations", array);
}
return json;
}
@Override
public String toString() {
return toJson().encode();
}
}
```
|
```package io.vertx.ext.auth.webauthn.impl.attestation;
import io.vertx.core.file.FileSystem;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.auth.webauthn.WebAuthnOptions;
import io.vertx.ext.auth.webauthn.impl.metadata.MetaData;
import io.vertx.ext.auth.webauthn.impl.metadata.MetaDataEntry;
import io.vertx.ext.unit.junit.RunTestOnContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(VertxUnitRunner.class)
public class MetadataTest {
@Rule
public final RunTestOnContext rule = new RunTestOnContext();
@Test
public void loadStatements() {
FileSystem fs = rule.vertx()
.fileSystem();
MetaData metadata = new MetaData(rule.vertx(), new WebAuthnOptions());
for (String f : fs.readDirBlocking("metadataStatements")) {
metadata.loadMetadata(new MetaDataEntry(new JsonObject(fs.readFileBlocking(f))));
}
}
}
```
|
Please help me generate a test for this class.
|
```package io.vertx.ext.auth.webauthn.impl.metadata;
import io.vertx.codegen.annotations.Nullable;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.core.shareddata.LocalMap;
import io.vertx.ext.auth.impl.CertificateHelper;
import io.vertx.ext.auth.impl.jose.JWS;
import io.vertx.ext.auth.webauthn.PublicKeyCredential;
import io.vertx.ext.auth.webauthn.WebAuthnOptions;
import io.vertx.ext.auth.webauthn.impl.attestation.AttestationException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SignatureException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* This class will hold the Fido2 Metadata Records.
*/
public final class MetaData {
private static final JsonArray EMTPY = new JsonArray(Collections.emptyList());
/**
* A mapping of ALG_SIGN hex values (as unsigned shorts) to COSE curve values. Keys should appear as
* values in a metadata statement's `authenticationAlgorithm` property.
* <p>
* From https://fidoalliance.org/specs/fido-v2.0-rd-20180702/fido-registry-v2.0-rd-20180702.html
* FIDO Registry of Predefined Values - 3.6.1 Authentication Algorithms
*/
public static final int ALG_SIGN_SECP256R1_ECDSA_SHA256_RAW = 0x0001;
public static final int ALG_SIGN_SECP256R1_ECDSA_SHA256_DER = 0x0002;
public static final int ALG_SIGN_RSASSA_PSS_SHA256_RAW = 0x0003;
public static final int ALG_SIGN_RSASSA_PSS_SHA256_DER = 0x0004;
public static final int ALG_SIGN_SECP256K1_ECDSA_SHA256_RAW = 0x0005;
public static final int ALG_SIGN_SECP256K1_ECDSA_SHA256_DER = 0x0006;
public static final int ALG_SIGN_RSASSA_PSS_SHA384_RAW = 0x000A;
public static final int ALG_SIGN_RSASSA_PSS_SHA512_RAW = 0x000B;
public static final int ALG_SIGN_RSASSA_PKCSV15_SHA256_RAW = 0x000C;
public static final int ALG_SIGN_RSASSA_PKCSV15_SHA384_RAW = 0x000D;
public static final int ALG_SIGN_RSASSA_PKCSV15_SHA512_RAW = 0x000E;
public static final int ALG_SIGN_RSASSA_PKCSV15_SHA1_RAW = 0x000F;
public static final int ALG_SIGN_SECP384R1_ECDSA_SHA384_RAW = 0x0010;
public static final int ALG_SIGN_SECP521R1_ECDSA_SHA512_RAW = 0x0011;
public static final int ALG_SIGN_ED25519_EDDSA_SHA256_RAW = 0x0012;
/**
* A map of ATTESTATION hex values (as unsigned shorts). Values should appear in a metadata
* statement's `attestationTypes` property.
* <p>
* From https://fidoalliance.org/specs/fido-v2.0-rd-20180702/fido-registry-v2.0-rd-20180702.html
* FIDO Registry of Predefined Values - 3.6.3 Authenticator Attestation Types
*/
public static final int ATTESTATION_BASIC_FULL = 0x3E07;
public static final int ATTESTATION_BASIC_SURROGATE = 0x3E08;
public static final int ATTESTATION_ECDAA = 0x3E09;
public static final int ATTESTATION_ATTCA = 0x3E0A;
public static final int ATTESTATION_ANONCA = 0x3E0C;
public static final int ATTESTATION_NONE = 0x3E0B;
private final LocalMap<String, MetaDataEntry> store;
private final WebAuthnOptions options;
public MetaData(Vertx vertx, WebAuthnOptions options) {
this.store = vertx.sharedData()
.getLocalMap(MetaData.class.getName());
this.options = options;
}
public MetaData clear() {
store.clear();
return this;
}
public int size() {
return store.size();
}
public @Nullable PublicKeyCredential toJOSEAlg(Integer fido2AlgSign) {
if (fido2AlgSign == null) {
return null;
}
switch (fido2AlgSign) {
case ALG_SIGN_SECP256R1_ECDSA_SHA256_RAW:
case ALG_SIGN_SECP256R1_ECDSA_SHA256_DER:
return PublicKeyCredential.ES256;
case ALG_SIGN_RSASSA_PSS_SHA256_RAW:
case ALG_SIGN_RSASSA_PSS_SHA256_DER:
return PublicKeyCredential.PS256;
case ALG_SIGN_SECP256K1_ECDSA_SHA256_RAW:
case ALG_SIGN_SECP256K1_ECDSA_SHA256_DER:
return PublicKeyCredential.ES256K;
case ALG_SIGN_RSASSA_PSS_SHA384_RAW:
return PublicKeyCredential.PS384;
case ALG_SIGN_RSASSA_PSS_SHA512_RAW:
return PublicKeyCredential.PS512;
case ALG_SIGN_RSASSA_PKCSV15_SHA256_RAW:
return PublicKeyCredential.RS256;
case ALG_SIGN_RSASSA_PKCSV15_SHA384_RAW:
return PublicKeyCredential.RS384;
case ALG_SIGN_RSASSA_PKCSV15_SHA512_RAW:
return PublicKeyCredential.RS512;
case ALG_SIGN_RSASSA_PKCSV15_SHA1_RAW:
return PublicKeyCredential.RS1;
case ALG_SIGN_SECP384R1_ECDSA_SHA384_RAW:
return PublicKeyCredential.ES384;
case ALG_SIGN_SECP521R1_ECDSA_SHA512_RAW:
return PublicKeyCredential.ES512;
case ALG_SIGN_ED25519_EDDSA_SHA256_RAW:
return PublicKeyCredential.EdDSA;
default:
return null;
}
}
public static @Nullable PublicKeyCredential toJOSEAlg(String fido2AlgSign) {
if (fido2AlgSign == null) {
return null;
}
switch (fido2AlgSign) {
case "secp256r1_ecdsa_sha256_raw":
case "secp256r1_ecdsa_sha256_der":
return PublicKeyCredential.ES256;
case "rsassa_pss_sha256_raw":
case "rsassa_pss_sha256_der":
return PublicKeyCredential.PS256;
case "secp256k1_ecdsa_sha256_raw":
case "secp256k1_ecdsa_sha256_der":
return PublicKeyCredential.ES256K;
case "rsassa_pss_sha384_raw":
return PublicKeyCredential.PS384;
case "rsassa_pss_sha512_raw":
return PublicKeyCredential.PS512;
case "rsassa_pkcsv15_sha256_raw":
return PublicKeyCredential.RS256;
case "rsassa_pkcsv15_sha384_raw":
return PublicKeyCredential.RS384;
case "rsassa_pkcsv15_sha512_raw":
return PublicKeyCredential.RS512;
case "rsassa_pkcsv15_sha1_raw":
return PublicKeyCredential.RS1;
case "secp384r1_ecdsa_sha384_raw":
return PublicKeyCredential.ES384;
case "secp521r1_ecdsa_sha512_raw":
return PublicKeyCredential.ES512;
case "ed25519_eddsa_sha256_raw":
return PublicKeyCredential.EdDSA;
default:
return null;
}
}
public JsonObject verifyMetadata(String aaguid, PublicKeyCredential alg, List<X509Certificate> x5c) throws MetaDataException, AttestationException, NoSuchProviderException, NoSuchAlgorithmException, InvalidKeyException, SignatureException, CertificateException {
return verifyMetadata(aaguid, alg, x5c, null, true);
}
public JsonObject verifyMetadata(String aaguid, PublicKeyCredential alg, List<X509Certificate> x5c, boolean includesRoot) throws MetaDataException, AttestationException, NoSuchProviderException, NoSuchAlgorithmException, InvalidKeyException, SignatureException, CertificateException {
return verifyMetadata(aaguid, alg, x5c, null, includesRoot);
}
public JsonObject verifyMetadata(String aaguid, PublicKeyCredential alg, List<X509Certificate> x5c, X509Certificate rootCert) throws MetaDataException, AttestationException, NoSuchProviderException, NoSuchAlgorithmException, InvalidKeyException, SignatureException, CertificateException {
return verifyMetadata(aaguid, alg, x5c, rootCert, true);
}
@Nullable
public JsonObject verifyMetadata(String aaguid, PublicKeyCredential alg, List<X509Certificate> x5c, X509Certificate rootCert, boolean includesRoot) throws MetaDataException, AttestationException, NoSuchProviderException, NoSuchAlgorithmException, InvalidKeyException, SignatureException, CertificateException {
// If available, validate attestation alg and x5c with info in the metadata statement
MetaDataEntry entry = store.get(aaguid);
if (entry != null) {
entry.checkValid();
// Make sure the alg in the attestation statement matches the one specified in the metadata
switch (entry.version()) {
case 2:
if (alg != toJOSEAlg(entry.statement().getInteger("authenticationAlgorithm"))) {
throw new AttestationException("Attestation alg did not match metadata auth alg");
}
break;
case 3:
// in MDS3 this field is an array
boolean found = false;
for (Object el : entry.statement().getJsonArray("authenticationAlgorithms", EMTPY)) {
if (alg == toJOSEAlg((String) el)) {
// OK
found = true;
break;
}
}
if (!found) {
throw new AttestationException("Attestation alg did not match metadata auth alg");
}
break;
default:
throw new AttestationException("Unsupported metadata version: " + entry.version());
}
if (x5c != null) {
// make a copy before we start
x5c = new ArrayList<>(x5c);
// Using MDS or Metadata Statements, for each attestationRoot in attestationRootCertificates:
// append attestation root to the end of the header.x5c, and try verifying certificate chain.
// If none succeed, throw an error
JsonArray attestationRootCertificates = entry.statement().getJsonArray("attestationRootCertificates");
if (attestationRootCertificates == null || attestationRootCertificates.size() == 0) {
if (rootCert != null) {
x5c.add(rootCert);
}
CertificateHelper.checkValidity(x5c, includesRoot, options.getRootCrls());
} else {
boolean chainValid = false;
for (int i = 0; i < attestationRootCertificates.size(); i++) {
try {
// add the metadata root certificate
x5c.add(JWS.parseX5c(attestationRootCertificates.getString(i)));
CertificateHelper.checkValidity(x5c, options.getRootCrls());
chainValid = true;
break;
} catch (CertificateException e) {
// remove the previously added certificate
x5c.remove(x5c.size() - 1);
// continue
}
}
if (!chainValid) {
throw new AttestationException("Certificate Chain not valid for metadata");
}
}
}
return entry.statement();
}
if (x5c != null) {
// make a copy before we start
x5c = new ArrayList<>(x5c);
if (rootCert != null) {
x5c.add(rootCert);
}
CertificateHelper.checkValidity(x5c, includesRoot, options.getRootCrls());
}
return null;
}
public MetaData loadMetadata(MetaDataEntry entry) {
JsonObject json = entry.statement();
String aaguid = json.getString("aaguid");
if ("fido2".equals(json.getString("protocolFamily"))) {
if (aaguid == null) {
throw new IllegalArgumentException("Statement doesn't contain {aaguid}");
}
store.put(aaguid, entry);
}
return this;
}
public static boolean statementAttestationTypesContains(JsonObject statement, int type) throws MetaDataException {
if (!statement.containsKey("attestationTypes")) {
return true;
}
final JsonArray attestationTypes = statement.getJsonArray("attestationTypes");
switch (statement.getInteger("schema", 2)) {
case 2:
return attestationTypes.contains(type);
case 3:
String stype;
switch (type) {
case ATTESTATION_BASIC_FULL:
stype = "basic_full";
break;
case ATTESTATION_BASIC_SURROGATE:
stype = "basic_surrogate";
break;
case ATTESTATION_ECDAA:
stype = "ecdaa";
break;
case ATTESTATION_ATTCA:
stype = "attca";
break;
case ATTESTATION_ANONCA:
stype = "anonca";
break;
case ATTESTATION_NONE:
stype = "none";
break;
default:
throw new IllegalArgumentException("Invalid type: " + type);
}
return attestationTypes.contains(stype);
default:
throw new MetaDataException("Unsupported metadata version");
}
}
}
```
|
```package io.vertx.ext.auth;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.HttpServer;
import io.vertx.ext.auth.authorization.AuthorizationContext;
import io.vertx.ext.auth.authorization.PermissionBasedAuthorization;
import io.vertx.ext.auth.authorization.WildcardPermissionBasedAuthorization;
import io.vertx.ext.auth.authorization.impl.AuthorizationContextImpl;
import io.vertx.ext.auth.authorization.impl.PermissionBasedAuthorizationConverter;
import io.vertx.ext.unit.Async;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.RunTestOnContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.Collections;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
@RunWith(VertxUnitRunner.class)
public class PermissionBasedAuthorizationTest {
@Rule
public final RunTestOnContext rule = new RunTestOnContext();
@Test
public void testConverter() {
TestUtils.testJsonCodec(PermissionBasedAuthorization.create("p1"), PermissionBasedAuthorizationConverter::encode,
PermissionBasedAuthorizationConverter::decode);
TestUtils.testJsonCodec(PermissionBasedAuthorization.create("p1").setResource("resource"),
PermissionBasedAuthorizationConverter::encode, PermissionBasedAuthorizationConverter::decode);
}
@Test
public void testImplies1() {
assertTrue(PermissionBasedAuthorization.create("p1").verify(PermissionBasedAuthorization.create("p1")));
}
@Test
public void testImplies2() {
assertTrue(PermissionBasedAuthorization.create("p1").setResource("r1")
.verify(PermissionBasedAuthorization.create("p1").setResource("r1")));
}
@Test
public void testImplies3() {
assertFalse(PermissionBasedAuthorization.create("p1").setResource("r1").verify(PermissionBasedAuthorization.create("p1")));
}
@Test
public void testImplies4() {
assertFalse(PermissionBasedAuthorization.create("p1").verify(PermissionBasedAuthorization.create("p1").setResource("r1")));
}
@Test
public void testImplies5() {
assertFalse(PermissionBasedAuthorization.create("p1").verify(PermissionBasedAuthorization.create("p2")));
}
@Test
public void testVerifyWildcard() {
assertTrue(PermissionBasedAuthorization.create("p1").verify(WildcardPermissionBasedAuthorization.create("p1")));
assertTrue(PermissionBasedAuthorization.create("p1.*").verify(WildcardPermissionBasedAuthorization.create("p1.*")));
}
@Test
public void testMatch1(TestContext should) {
final Async test = should.async();
final HttpServer server = rule.vertx().createHttpServer();
server.requestHandler(request -> {
User user = User.fromName("dummy user");
user.authorizations().put("providerId", PermissionBasedAuthorization.create("p1").setResource("r1"));
AuthorizationContext context = new AuthorizationContextImpl(user, request.params());
should.assertEquals(true, PermissionBasedAuthorization.create("p1").setResource("{variable1}").match(context));
request.response().end();
}).listen(0, "localhost").onComplete(should.asyncAssertSuccess(s -> {
rule.vertx().createHttpClient().request(HttpMethod.GET, s.actualPort(), "localhost", "/?variable1=r1").onComplete(should.asyncAssertSuccess(req -> {
req.send().onComplete(should.asyncAssertSuccess(res -> {
server.close().onComplete(close -> test.complete());
}));
}));
}));
}
@Test
public void testMatch2(TestContext should) {
final Async test = should.async();
final HttpServer server = rule.vertx().createHttpServer();
server.requestHandler(request -> {
User user = User.fromName("dummy user");
user.authorizations().put("providerId", PermissionBasedAuthorization.create("p1").setResource("r1"));
AuthorizationContext context = new AuthorizationContextImpl(user, request.params());
should.assertEquals(false, PermissionBasedAuthorization.create("p1").setResource("{variable1}").match(context));
request.response().end();
}).listen(0, "localhost").onComplete(should.asyncAssertSuccess(s -> {
rule.vertx().createHttpClient().request(HttpMethod.GET, s.actualPort(), "localhost", "/?variable1=r2").onComplete(should.asyncAssertSuccess(req -> {
req.send().onComplete(should.asyncAssertSuccess(res -> {
server.close().onComplete(close -> test.complete());
}));
}));
}));
}
}
```
|
Please help me generate a test for this class.
|
```package io.vertx.ext.auth.authorization;
import io.vertx.codegen.annotations.Fluent;
import io.vertx.codegen.annotations.VertxGen;
import io.vertx.ext.auth.authorization.impl.PermissionBasedAuthorizationImpl;
/**
* Represents a permission Note that the permission can optionally be assigned
* to a specific resource
*
* @author <a href="mail://stephane.bastian.dev@gmail.com">Stephane Bastian</a>
*/
@VertxGen
public interface PermissionBasedAuthorization extends Authorization {
static PermissionBasedAuthorization create(String permission) {
return new PermissionBasedAuthorizationImpl(permission);
}
/**
* returns the value of the permission
*
* @return
*/
String getPermission();
/**
* returns an optional resource that the permission is assigned-on
*
* @return
*/
String getResource();
/**
* sets an optional resource that the permission is assigned-on
*
* @return
*/
@Fluent
PermissionBasedAuthorization setResource(String resource);
}
```
|
```package io.vertx.ext.auth.webauthn;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.unit.Async;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.RunTestOnContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertNotNull;
@RunWith(VertxUnitRunner.class)
public class NavigatorCredentialsCreate {
private final DummyStore database = new DummyStore();
@Rule
public final RunTestOnContext rule = new RunTestOnContext();
@Before
public void resetDatabase() {
database.clear();
}
@Test
public void testRequestRegister(TestContext should) {
final Async test = should.async();
WebAuthn webAuthN = WebAuthn.create(
rule.vertx(),
new WebAuthnOptions().setRelyingParty(new RelyingParty().setName("ACME Corporation"))
.setAttestation(Attestation.of("direct")))
.authenticatorFetcher(database::fetch)
.authenticatorUpdater(database::store);
// Dummy user
JsonObject user = new JsonObject()
// id is expected to be a base64url string
.put("id", "000000000000000000000000")
.put("name", "john.doe@email.com")
.put("displayName", "John Doe")
.put("icon", "https://pics.example.com/00/p/aBjjjpqPb.png");
webAuthN
.createCredentialsOptions(user)
.onFailure(should::fail)
.onSuccess(challengeResponse -> {
assertNotNull(challengeResponse);
// important fields to be present
assertNotNull(challengeResponse.getString("challenge"));
assertNotNull(challengeResponse.getJsonObject("rp"));
assertNotNull(challengeResponse.getJsonObject("user"));
assertNotNull(challengeResponse.getJsonArray("pubKeyCredParams"));
// ensure that challenge and user.id are base64url encoded
assertNotNull(challengeResponse.getBinary("challenge"));
assertNotNull(challengeResponse.getJsonObject("user").getBinary("id"));
test.complete();
});
}
@Test
public void testRegister(TestContext should) {
final Async test = should.async();
WebAuthn webAuthN = WebAuthn.create(
rule.vertx(),
new WebAuthnOptions().setRelyingParty(new RelyingParty().setName("ACME Corporation")))
.authenticatorFetcher(database::fetch)
.authenticatorUpdater(database::store);
// dummy request
JsonObject request = new JsonObject()
.put("id", "Q-MHP0Xq20CKM5LW3qBt9gu5vdOYLNZc3jCcgyyLncRav5Ivd7T1dav3eWrI7CT8HmzU_yAYJrmja4in8OFL3A")
.put("rawId", "Q-MHP0Xq20CKM5LW3qBt9gu5vdOYLNZc3jCcgyyLncRav5Ivd7T1dav3eWrI7CT8HmzU_yAYJrmja4in8OFL3A")
.put("type", "public-key")
.put("response", new JsonObject()
.put("attestationObject", "o2NmbXRkbm9uZWdhdHRTdG10oGhhdXRoRGF0YVjEfxV8VVBPmz66RLzscHpg5yjRhO28Y_fPwYO5AVwzBEJBAAAAAwAAAAAAAAAAAAAAAAAAAAAAQEPjBz9F6ttAijOS1t6gbfYLub3TmCzWXN4wnIMsi53EWr-SL3e09XWr93lqyOwk_B5s1P8gGCa5o2uIp_DhS9ylAQIDJiABIVggN_D3u-03a0GzONOHfaML881QZtOCc5oTNRB2wlyqUEUiWCD3878XoO_bIJf0mEPDILODFhVmkc4QeR6hOIDvwvXzYQ")
.put("clientDataJSON", "eyJ0eXBlIjoid2ViYXV0aG4uY3JlYXRlIiwiY2hhbGxlbmdlIjoiQkg3RUtJRFhVNkN0Xzk2eFR6RzBsNjJxTWhXX0VmX0s0TVFkRExvVk5jMVVYTVFZNHFOOWFnNXlETm1MSTd2RlJzbGtRYmJqMEpaV0p4R1ZmTXVnWGciLCJvcmlnaW4iOiJodHRwczovLzE5Mi4xNjguMTc4LjIwNi54aXAuaW86ODQ0MyIsImNyb3NzT3JpZ2luIjpmYWxzZX0"));
webAuthN
.authenticate(
new WebAuthnCredentials()
.setUsername("paulo")
.setOrigin("https://192.168.178.206.xip.io:8443")
.setDomain("192.168.178.206.xip.io")
.setChallenge("BH7EKIDXU6Ct_96xTzG0l62qMhW_Ef_K4MQdDLoVNc1UXMQY4qN9ag5yDNmLI7vFRslkQbbj0JZWJxGVfMugXg")
.setWebauthn(request))
.onFailure(should::fail)
.onSuccess(response -> {
assertNotNull(response);
test.complete();
});
}
}
```
|
Please help me generate a test for this class.
|
```package io.vertx.ext.auth.oauth2;
import io.vertx.codegen.annotations.DataObject;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.auth.authentication.CredentialValidationException;
import io.vertx.ext.auth.authentication.Credentials;
import java.util.ArrayList;
import java.util.List;
/**
* Credentials specific to the {@link OAuth2Auth} provider
*
* @author <a href="mailto:pmlopes@gmail.com">Paulo Lopes</a>
*/
@DataObject(generateConverter = true)
public class Oauth2Credentials implements Credentials {
// swap code for token
private String code;
private String redirectUri;
private String codeVerifier;
// jwt-bearer
// tokens can include other kind of generic data
private JsonObject jwt;
// or contain an assertion
private String assertion;
// password credentials
private String password;
private String username;
// control state
private List<String> scopes;
private OAuth2FlowType flow;
public Oauth2Credentials() {
}
public Oauth2Credentials(JsonObject json) {
Oauth2CredentialsConverter.fromJson(json, this);
}
public String getCode() {
return code;
}
public Oauth2Credentials setCode(String code) {
this.code = code;
return this;
}
public String getRedirectUri() {
return redirectUri;
}
public Oauth2Credentials setRedirectUri(String redirectUri) {
this.redirectUri = redirectUri;
return this;
}
public String getCodeVerifier() {
return codeVerifier;
}
public Oauth2Credentials setCodeVerifier(String codeVerifier) {
this.codeVerifier = codeVerifier;
return this;
}
public List<String> getScopes() {
return scopes;
}
public Oauth2Credentials addScope(String scope) {
if (this.scopes == null) {
this.scopes = new ArrayList<>();
}
this.scopes.add(scope);
return this;
}
public Oauth2Credentials setScopes(List<String> scopes) {
this.scopes = scopes;
return this;
}
public JsonObject getJwt() {
return jwt;
}
public Oauth2Credentials setJwt(JsonObject jwt) {
this.jwt = jwt;
return this;
}
public String getAssertion() {
return assertion;
}
public Oauth2Credentials setAssertion(String assertion) {
this.assertion = assertion;
return this;
}
public String getPassword() {
return password;
}
public Oauth2Credentials setPassword(String password) {
this.password = password;
return this;
}
public String getUsername() {
return username;
}
public Oauth2Credentials setUsername(String username) {
this.username = username;
return this;
}
public OAuth2FlowType getFlow() {
return flow;
}
public Oauth2Credentials setFlow(OAuth2FlowType flow) {
this.flow = flow;
return this;
}
@Override
public JsonObject toJson() {
final JsonObject json = new JsonObject();
Oauth2CredentialsConverter.toJson(this, json);
return json;
}
@Override
public <V> void checkValid(V arg) throws CredentialValidationException {
if (flow == null) {
throw new CredentialValidationException("flow cannot be null");
}
// when there's no access token, validation shall be performed according to each flow
switch (flow) {
case CLIENT:
// no fields are required
break;
case AUTH_CODE:
if (code == null || code.length() == 0) {
throw new CredentialValidationException("code cannot be null or empty");
}
if (redirectUri != null && redirectUri.length() == 0) {
throw new CredentialValidationException("redirectUri cannot be empty");
}
break;
case AUTH_JWT:
if (jwt == null) {
throw new CredentialValidationException("jwt cannot be null");
}
break;
case AAD_OBO:
if (assertion == null || assertion.length() == 0) {
throw new CredentialValidationException("assertion cannot be null or empty");
}
break;
case PASSWORD:
if (username == null || username.length() == 0) {
throw new CredentialValidationException("username cannot be null or empty");
}
if (password == null || password.length() == 0) {
throw new CredentialValidationException("password cannot be null or empty");
}
break;
}
}
@Override
public String toString() {
return toJson().encode();
}
}
```
|
```package io.vertx.ext.auth;
import io.vertx.ext.auth.authorization.AndAuthorization;
import io.vertx.ext.auth.authorization.PermissionBasedAuthorization;
import org.junit.Assert;
import org.junit.Test;
public class AndAuthorizationTest {
@Test
public void testImpliesOk1() {
Assert.assertEquals(true, AndAuthorization.create().addAuthorization(PermissionBasedAuthorization.create("p1"))
.verify(AndAuthorization.create().addAuthorization(PermissionBasedAuthorization.create("p1"))));
}
@Test
public void testImpliesOk2() {
Assert.assertEquals(true, AndAuthorization.create().addAuthorization(PermissionBasedAuthorization.create("p1"))
.verify(PermissionBasedAuthorization.create("p1")));
}
@Test
public void testImpliesOk3() {
Assert.assertEquals(true,
AndAuthorization.create().addAuthorization(PermissionBasedAuthorization.create("p1"))
.addAuthorization(PermissionBasedAuthorization.create("p2"))
.verify(AndAuthorization.create().addAuthorization(PermissionBasedAuthorization.create("p1"))
.addAuthorization(PermissionBasedAuthorization.create("p2"))));
}
@Test
public void testImpliesOk4() {
Assert.assertEquals(true,
AndAuthorization.create().addAuthorization(PermissionBasedAuthorization.create("p1"))
.addAuthorization(PermissionBasedAuthorization.create("p2"))
.verify(AndAuthorization.create().addAuthorization(PermissionBasedAuthorization.create("p1"))));
}
@Test
public void testImpliesOk5() {
Assert.assertEquals(true, AndAuthorization.create().addAuthorization(PermissionBasedAuthorization.create("p1"))
.addAuthorization(PermissionBasedAuthorization.create("p2")).verify(PermissionBasedAuthorization.create("p1")));
}
@Test
public void testImpliesKo1() {
Assert.assertEquals(false, AndAuthorization.create().addAuthorization(PermissionBasedAuthorization.create("p1"))
.verify(AndAuthorization.create().addAuthorization(PermissionBasedAuthorization.create("p2"))));
}
@Test
public void testImpliesKo2() {
Assert.assertEquals(false, AndAuthorization.create().addAuthorization(PermissionBasedAuthorization.create("p1"))
.verify(PermissionBasedAuthorization.create("p2")));
}
}
```
|
Please help me generate a test for this class.
|
```package io.vertx.ext.auth.authorization;
import io.vertx.codegen.annotations.VertxGen;
import io.vertx.ext.auth.authorization.impl.AndAuthorizationImpl;
import java.util.List;
/**
* Allows to perform a logical 'and' between several authorizations
*
* @author <a href="mailto:stephane.bastian.dev@gmail.com">Stephane Bastian</a>
*/
@VertxGen
public interface AndAuthorization extends Authorization {
static AndAuthorization create() {
return new AndAuthorizationImpl();
}
List<Authorization> getAuthorizations();
AndAuthorization addAuthorization(Authorization authorization);
}
```
|
```package io.vertx.ext.auth;
import io.vertx.ext.auth.authorization.OrAuthorization;
import io.vertx.ext.auth.authorization.PermissionBasedAuthorization;
import org.junit.Assert;
import org.junit.Test;
public class OrAuthorizationTest {
@Test
public void testImpliesOk1() {
Assert.assertEquals(true, OrAuthorization.create().addAuthorization(PermissionBasedAuthorization.create("p1"))
.verify(OrAuthorization.create().addAuthorization(PermissionBasedAuthorization.create("p1"))));
}
@Test
public void testImpliesOk2() {
Assert.assertEquals(true, OrAuthorization.create().addAuthorization(PermissionBasedAuthorization.create("p1"))
.verify(PermissionBasedAuthorization.create("p1")));
}
@Test
public void testImpliesOk3() {
Assert.assertEquals(true,
OrAuthorization.create().addAuthorization(PermissionBasedAuthorization.create("p1"))
.addAuthorization(PermissionBasedAuthorization.create("p2"))
.verify(OrAuthorization.create().addAuthorization(PermissionBasedAuthorization.create("p1"))
.addAuthorization(PermissionBasedAuthorization.create("p2"))));
}
@Test
public void testImpliesKo1() {
Assert.assertEquals(false, OrAuthorization.create().addAuthorization(PermissionBasedAuthorization.create("p1"))
.verify(OrAuthorization.create().addAuthorization(PermissionBasedAuthorization.create("p2"))));
}
@Test
public void testImpliesKo2() {
Assert.assertEquals(false, OrAuthorization.create().addAuthorization(PermissionBasedAuthorization.create("p1"))
.verify(PermissionBasedAuthorization.create("p2")));
}
@Test
public void testImpliesKo3() {
Assert.assertEquals(false,
OrAuthorization.create().addAuthorization(PermissionBasedAuthorization.create("p1"))
.addAuthorization(PermissionBasedAuthorization.create("p2"))
.verify(OrAuthorization.create().addAuthorization(PermissionBasedAuthorization.create("p1"))));
}
}
```
|
Please help me generate a test for this class.
|
```package io.vertx.ext.auth.authorization;
import io.vertx.codegen.annotations.VertxGen;
import io.vertx.ext.auth.authorization.impl.OrAuthorizationImpl;
import java.util.List;
/**
* Allows to perform a logical 'or' between several authorizations
*
* @author <a href="mailto:stephane.bastian.dev@gmail.com">Stephane Bastian</a>
*/
@VertxGen
public interface OrAuthorization extends Authorization {
static OrAuthorization create() {
return new OrAuthorizationImpl();
}
List<Authorization> getAuthorizations();
OrAuthorization addAuthorization(Authorization authorization);
}
```
|
```package io.vertx.ext.auth;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.HttpServer;
import io.vertx.ext.auth.authorization.AuthorizationContext;
import io.vertx.ext.auth.authorization.PermissionBasedAuthorization;
import io.vertx.ext.auth.authorization.WildcardPermissionBasedAuthorization;
import io.vertx.ext.auth.authorization.impl.AuthorizationContextImpl;
import io.vertx.ext.auth.authorization.impl.WildcardPermissionBasedAuthorizationConverter;
import io.vertx.ext.unit.Async;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.RunTestOnContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.Collections;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
@RunWith(VertxUnitRunner.class)
public class WildcardPermissionBasedAuthorizationTest {
@Rule
public final RunTestOnContext rule = new RunTestOnContext();
@Test
public void testConverter() {
TestUtils.testJsonCodec(WildcardPermissionBasedAuthorization.create("wp1"),
WildcardPermissionBasedAuthorizationConverter::encode, WildcardPermissionBasedAuthorizationConverter::decode);
TestUtils.testJsonCodec(WildcardPermissionBasedAuthorization.create("wp1").setResource("resource"),
WildcardPermissionBasedAuthorizationConverter::encode, WildcardPermissionBasedAuthorizationConverter::decode);
}
@Test
public void testImplies1() {
assertTrue(WildcardPermissionBasedAuthorization.create("wp1").verify(WildcardPermissionBasedAuthorization.create("wp1")));
}
@Test
public void testImplies2() {
assertTrue(WildcardPermissionBasedAuthorization.create("*").verify(WildcardPermissionBasedAuthorization.create("wp1")));
}
@Test
public void testImplies3() {
assertTrue(WildcardPermissionBasedAuthorization.create("printer:*")
.verify(WildcardPermissionBasedAuthorization.create("printer:read")));
}
@Test
public void testImplies4() {
assertTrue(WildcardPermissionBasedAuthorization.create("*:read")
.verify(WildcardPermissionBasedAuthorization.create("printer:read")));
}
@Test
public void testImplies5() {
assertTrue(WildcardPermissionBasedAuthorization.create("p1")
.verify(WildcardPermissionBasedAuthorization.create("p1").setResource("r1")));
}
@Test
public void testImplies6() {
assertFalse(WildcardPermissionBasedAuthorization.create("p1").setResource("r1")
.verify(WildcardPermissionBasedAuthorization.create("p1")));
}
@Test
public void testImplies7() {
assertFalse(WildcardPermissionBasedAuthorization.create("wp1").verify(WildcardPermissionBasedAuthorization.create("wp2")));
}
@Test
public void testImplies8() {
assertFalse(WildcardPermissionBasedAuthorization.create("printer:read")
.verify(WildcardPermissionBasedAuthorization.create("*")));
}
@Test
public void testImplies9() {
assertFalse(WildcardPermissionBasedAuthorization.create("*:read")
.verify(WildcardPermissionBasedAuthorization.create("printer:edit")));
}
@Test
public void testVerifyPermisionAuthorization() {
assertTrue(WildcardPermissionBasedAuthorization.create("p1").verify(PermissionBasedAuthorization.create("p1")));
assertTrue(WildcardPermissionBasedAuthorization.create("p1.*").verify(PermissionBasedAuthorization.create("p1.*")));
assertTrue(WildcardPermissionBasedAuthorization.create("*").verify(PermissionBasedAuthorization.create("*")));
assertTrue(WildcardPermissionBasedAuthorization.create("*").verify(PermissionBasedAuthorization.create("test")));
}
@Test
public void testMatch1(TestContext should) {
final Async test = should.async();
final HttpServer server = rule.vertx().createHttpServer();
server.requestHandler(request -> {
User user = User.fromName("dummy user");
user.authorizations().put("providerId", WildcardPermissionBasedAuthorization.create("p1").setResource("r1"));
AuthorizationContext context = new AuthorizationContextImpl(user, request.params());
should.assertTrue(WildcardPermissionBasedAuthorization.create("p1").setResource("{variable1}").match(context));
request.response().end();
}).listen(0, "localhost").onComplete(should.asyncAssertSuccess(s -> {
rule.vertx().createHttpClient().request(HttpMethod.GET, s.actualPort(), "localhost", "/?variable1=r1").onComplete(should.asyncAssertSuccess(req -> {
req.send().onComplete(should.asyncAssertSuccess(res -> {
server.close().onComplete(close -> test.complete());
}));
}));
}));
}
@Test
public void testMatch2(TestContext should) {
final Async test = should.async();
final HttpServer server = rule.vertx().createHttpServer();
server.requestHandler(request -> {
User user = User.fromName("dummy user");
user.authorizations().put("providerId", WildcardPermissionBasedAuthorization.create("p1").setResource("r1"));
AuthorizationContext context = new AuthorizationContextImpl(user, request.params());
should.assertFalse(WildcardPermissionBasedAuthorization.create("p1").setResource("{variable1}").match(context));
request.response().end();
}).listen(0, "localhost").onComplete(should.asyncAssertSuccess(s -> {
rule.vertx().createHttpClient().request(HttpMethod.GET, s.actualPort(), "localhost", "/?variable1=r2").onComplete(should.asyncAssertSuccess(req -> {
req.send().onComplete(should.asyncAssertSuccess(res -> {
server.close().onComplete(close -> test.complete());
}));
}));
}));
}
}
```
|
Please help me generate a test for this class.
|
```package io.vertx.ext.auth.authorization;
import io.vertx.codegen.annotations.Fluent;
import io.vertx.codegen.annotations.VertxGen;
import io.vertx.ext.auth.authorization.impl.WildcardPermissionBasedAuthorizationImpl;
/**
* Represents a wildcard permission (ie: 'manage:order:*' '*:orders', '*', etc.)
* Note that it can optionally be assigned to a specific resource
*
* @author <a href="mail://stephane.bastian.dev@gmail.com">Stephane Bastian</a>
*/
@VertxGen
public interface WildcardPermissionBasedAuthorization extends Authorization {
static WildcardPermissionBasedAuthorization create(String permission) {
return new WildcardPermissionBasedAuthorizationImpl(permission);
}
/**
* return the value of the wildcard permission
*
* @return
*/
String getPermission();
/**
* returns an optional resource that the permission is assigned-on
*
* @return
*/
String getResource();
/**
* sets an optional resource that the permission is assigned-on
*
* @return
*/
@Fluent
WildcardPermissionBasedAuthorization setResource(String resource);
}
```
|
```package io.vertx.ext.auth;
import io.vertx.core.Context;
import io.vertx.core.Vertx;
import io.vertx.ext.unit.junit.RunTestOnContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.lang.reflect.Proxy;
import static org.junit.Assert.assertNotNull;
@RunWith(VertxUnitRunner.class)
public class VertxContextPRNGTest {
@Rule
public final RunTestOnContext rule = new RunTestOnContext();
@Test
public void testPRNGQuarkusContextAccessNotAllowed() {
final Vertx vertx = rule.vertx();
Context context = (Context) Proxy.newProxyInstance(
VertxContextPRNGTest.class.getClassLoader(),
new Class[]{Context.class},
(proxy, method, methodArgs) -> {
switch (method.getName()) {
case "get":
case "put":
case "remove":
// mimic Quarkus behavior
throw new UnsupportedOperationException("Access to Context.put(), Context.get() and Context.remove() are forbidden as it can leak data between unrelated processing. Use Context.putLocal(), Context.getLocal() and Context.removeLocal() instead. Note that these methods can only be used from a 'duplicated' Context, and so may not be available everywhere.");
case "owner":
return vertx;
case "equals":
return false;
default:
return null;
}
});
assertNotNull(VertxContextPRNG.current(context));
}
}
```
|
Please help me generate a test for this class.
|
```package io.vertx.ext.auth;
import io.vertx.codegen.annotations.GenIgnore;
import io.vertx.codegen.annotations.VertxGen;
import io.vertx.core.Context;
import io.vertx.core.Vertx;
import java.util.Objects;
import static io.vertx.codegen.annotations.GenIgnore.PERMITTED_TYPE;
/**
* A secure non blocking random number generator isolated to the current context. The PRNG is bound to the vert.x
* context and setup to close when the context shuts down.
* <p>
* When applicable, use of VertxContextPRNG rather than create new PRNG objects is helpful to keep the system entropy
* usage to the minimum avoiding potential blocking across the application.
* <p>
* The use of VertxContextPRNG is particularly appropriate when multiple handlers use random numbers.
*
* @author <a href="mailto:plopes@redhat.com">Paulo Lopes</a>
*/
@VertxGen
public interface VertxContextPRNG {
/**
* Get or create a secure non blocking random number generator using the current vert.x context. If there is no
* current context (i.e.: not running on the eventloop) then a {@link java.lang.IllegalStateException} is thrown.
* <p>
* Note, if a context isn't allowed to be used, for example, exceptions are thrown on getting and putting data,
* the VertxContextPRNG falls back to instantiate a new instance of the PRNG per call.
*
* @return A secure non blocking random number generator.
* @throws IllegalStateException when there is no {@link Context} instance available.
*/
static VertxContextPRNG current() {
final Context currentContext = Vertx.currentContext();
if (currentContext != null) {
return current(currentContext);
}
throw new IllegalStateException("Not running in a Vert.x Context.");
}
/**
* Get or create a secure non blocking random number generator using the provided vert.x context. This method will not
* throw an exception.
* <p>
* Note, if a context isn't allowed to be used, for example, exceptions are thrown on getting and putting data,
* the VertxContextPRNG falls back to instantiate a new instance of the PRNG per call.
*
* @param context a Vert.x context.
* @return A secure non blocking random number generator
* @throws IllegalStateException when there is no {@link Vertx} instance available.
*/
@GenIgnore
static VertxContextPRNG current(final Context context) {
Objects.requireNonNull(context, "context can not be null");
try {
final String contextKey = "__vertx.VertxContextPRNG";
// attempt to load a PRNG from the current context
PRNG random = context.get(contextKey);
if (random == null) {
synchronized (context) {
// attempt to reload to avoid double creation when we were
// waiting for the lock
random = context.get(contextKey);
if (random == null) {
// there was no PRNG in the context, create one
random = new PRNG(context.owner());
// need to make the random final
final PRNG rand = random;
// save to the context
context.put(contextKey, rand);
}
}
}
return random;
} catch (UnsupportedOperationException e) {
// Access to the current context is probably blocked
Vertx vertx = context.owner();
if (vertx != null) {
return new PRNG(vertx);
}
// vert.x cannot be null
throw new IllegalStateException("Not running in a Vert.x Context.");
}
}
/**
* Get or create a secure non blocking random number generator using the current vert.x instance. Since the context
* might be different this method will attempt to use the current context first if available and then fall back to
* create a new instance of the PRNG.
* <p>
* Note, if a context isn't allowed to be used, for example, exceptions are thrown on getting and putting data,
* the VertxContextPRNG falls back to instantiate a new instance of the PRNG per call.
*
* @param vertx a Vert.x instance.
* @return A secure non blocking random number generator.
*/
static VertxContextPRNG current(final Vertx vertx) {
final Context currentContext = Vertx.currentContext();
if (currentContext != null) {
return current(currentContext);
}
Objects.requireNonNull(vertx, "vertx can not be null");
// we are not running on a vert.x context, fallback to create a new instance
return new PRNG(vertx);
}
/**
* stop seeding the PRNG
*/
void close();
/**
* Fills the given byte array with random bytes.
*
* @param bytes a byte array.
*/
@GenIgnore(PERMITTED_TYPE)
void nextBytes(byte[] bytes);
/**
* Returns a Base64 url encoded String of random data with the given length. The length parameter refers to the length
* of the String before the encoding step.
*
* @param length the desired string length before Base64 encoding.
* @return A base 64 encoded string.
*/
String nextString(int length);
/**
* Returns a secure random int
*
* @return random int.
*/
int nextInt();
/**
* Returns a secure random int, between 0 (inclusive) and the specified bound (exclusive).
*
* @param bound the upper bound (exclusive), which must be positive.
* @return random int.
*/
int nextInt(int bound);
/**
* Returns a secure random boolean
*
* @return random boolean.
*/
boolean nextBoolean();
/**
* Returns a secure random long
*
* @return random long.
*/
long nextLong();
/**
* Returns a secure random float value. The value is uniformly distributed between 0.0 and 1.0
*
* @return random float.
*/
float nextFloat();
/**
* Returns a secure random double value. The value is uniformly distributed between 0.0 and 1.0
*
* @return random double.
*/
double nextDouble();
/**
* Returns a secure random double value. The value is Gaussian ("normally") distributed
* with mean 0.0 and standard deviation 1.0
*
* @return random double.
*/
double nextGaussian();
}
```
|
```package io.vertx.ext.auth.impl;
import org.junit.Test;
import java.nio.charset.StandardCharsets;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
public class CodecTest {
@Test
public void testBase32() {
String source = "The quick brown fox jumps over the lazy dog.";
assertEquals(
"KRUGKIDROVUWG2ZAMJZG653OEBTG66BANJ2W24DTEBXXMZLSEB2GQZJANRQXU6JAMRXWOLQ",
Codec.base32Encode(source.getBytes(StandardCharsets.UTF_8))
);
}
@Test
public void testBase16() {
byte[] source = "The quick brown fox jumps over the lazy dog.".getBytes(StandardCharsets.UTF_8);
assertArrayEquals(
source,
Codec.base16Decode(Codec.base16Encode(source))
);
}
}
```
|
Please help me generate a test for this class.
|
```package io.vertx.ext.auth.impl;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
/**
* A collection of simple codecs to avoid code duplication across modules.
* <p>
* This helper provies codecs for Base16, Base32 and Base64.
*
* @author Paulo Lopes
*/
public final class Codec {
private Codec() {
}
private static final byte[] BASE16 = "0123456789abcdef".getBytes(StandardCharsets.US_ASCII);
private static final int[] BASE16_LOOKUP =
{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0xFF
};
private static final char[] BASE32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".toCharArray();
private static final int[] BASE32_LOOKUP =
{0xFF, 0xFF, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06,
0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E,
0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16,
0x17, 0x18, 0x19, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06,
0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E,
0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16,
0x17, 0x18, 0x19, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
};
private static final Base64.Encoder BASE64URL = Base64.getUrlEncoder().withoutPadding();
private static final Base64.Decoder BASE64URL_DECODER = Base64.getUrlDecoder();
private static final Base64.Encoder BASE64 = Base64.getEncoder();
private static final Base64.Encoder BASE64_NOPADDING = Base64.getEncoder().withoutPadding();
private static final Base64.Decoder BASE64_DECODER = Base64.getDecoder();
private static final Base64.Encoder BASE64MIME = Base64.getMimeEncoder();
private static final Base64.Decoder BASE64MIME_DECODER = Base64.getMimeDecoder();
public static String base16Encode(byte[] bytes) {
byte[] base16 = new byte[bytes.length * 2];
for (int i = 0; i < bytes.length; i++) {
int v = bytes[i] & 0xFF;
base16[i * 2] = BASE16[v >>> 4];
base16[i * 2 + 1] = BASE16[v & 0x0F];
}
return new String(base16, StandardCharsets.ISO_8859_1);
}
public static byte[] base16Decode(String base16) {
int lookup;
byte[] bytes = new byte[base16.length() / 2];
for (int i = 0; i < base16.length(); i += 2) {
lookup = base16.charAt(i) - '0';
/* chars outside the lookup table */
if (lookup < 0 || lookup >= BASE16_LOOKUP.length) {
throw new IllegalArgumentException("Invalid char: " + (base16.charAt(i)));
}
int high = BASE16_LOOKUP[lookup];
/* If this digit is not in the table, fail */
if (high == 0xFF) {
throw new IllegalArgumentException("Invalid char: " + (base16.charAt(i)));
}
lookup = base16.charAt(i + 1) - '0';
/* chars outside the lookup table */
if (lookup < 0 || lookup >= BASE16_LOOKUP.length) {
throw new IllegalArgumentException("Invalid char: " + (base16.charAt(i + 1)));
}
int low = BASE16_LOOKUP[lookup];
/* If this digit is not in the table, fail */
if (low == 0xFF) {
throw new IllegalArgumentException("Invalid char: " + (base16.charAt(i + 1)));
}
bytes[i / 2] = (byte) ((high << 4) + low);
}
return bytes;
}
public static String base32Encode(byte[] bytes) {
int i = 0, index = 0, digit;
int currByte, nextByte;
StringBuilder base32 = new StringBuilder(((bytes.length + 7) * 8 / 5));
while (i < bytes.length) {
currByte = (bytes[i] >= 0) ? bytes[i] : (bytes[i] + 256);
/* Is the current digit going to span a byte boundary? */
if (index > 3) {
if ((i + 1) < bytes.length) {
nextByte = (bytes[i + 1] >= 0)
? bytes[i + 1] : (bytes[i + 1] + 256);
} else {
nextByte = 0;
}
digit = currByte & (0xFF >> index);
index = (index + 5) % 8;
digit <<= index;
digit |= nextByte >> (8 - index);
i++;
} else {
digit = (currByte >> (8 - (index + 5))) & 0x1F;
index = (index + 5) % 8;
if (index == 0)
i++;
}
base32.append(BASE32[digit]);
}
return base32.toString();
}
static public byte[] base32Decode(final String base32) {
int i, index, lookup, offset, digit;
byte[] bytes = new byte[base32.length() * 5 / 8];
for (i = 0, index = 0, offset = 0; i < base32.length(); i++) {
lookup = base32.charAt(i) - '0';
/* Fail if chars outside the lookup table */
if (lookup < 0 || lookup >= BASE32_LOOKUP.length) {
throw new IllegalArgumentException("Invalid char: " + (base32.charAt(i)));
}
digit = BASE32_LOOKUP[lookup];
/* If this digit is not in the table, fail */
if (digit == 0xFF) {
throw new IllegalArgumentException("Invalid char: " + (base32.charAt(i)));
}
if (index <= 3) {
index = (index + 5) % 8;
if (index == 0) {
bytes[offset] |= digit;
offset++;
if (offset >= bytes.length)
break;
} else {
bytes[offset] |= digit << (8 - index);
}
} else {
index = (index + 5) % 8;
bytes[offset] |= (digit >>> index);
offset++;
if (offset >= bytes.length) {
break;
}
bytes[offset] |= digit << (8 - index);
}
}
return bytes;
}
public static String base64UrlEncode(byte[] bytes) {
return BASE64URL.encodeToString(bytes);
}
public static byte[] base64UrlDecode(String base64) {
return BASE64URL_DECODER.decode(base64);
}
public static byte[] base64UrlDecode(byte[] base64) {
return BASE64URL_DECODER.decode(base64);
}
public static String base64Encode(byte[] bytes) {
return BASE64.encodeToString(bytes);
}
public static String base64EncodeWithoutPadding(byte[] bytes) {
return BASE64_NOPADDING.encodeToString(bytes);
}
public static byte[] base64Decode(String base64) {
return BASE64_DECODER.decode(base64);
}
public static byte[] base64Decode(byte[] base64) {
return BASE64_DECODER.decode(base64);
}
public static String base64MimeEncode(byte[] bytes) {
return BASE64MIME.encodeToString(bytes);
}
public static byte[] base64MimeDecode(String base64) {
return BASE64MIME_DECODER.decode(base64);
}
public static byte[] base64MimeDecode(byte[] base64) {
return BASE64MIME_DECODER.decode(base64);
}
}
```
|
```package io.vertx.ext.auth;
import io.vertx.ext.auth.impl.Codec;
import io.vertx.ext.unit.junit.RunTestOnContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import static org.junit.Assert.*;
@RunWith(VertxUnitRunner.class)
public class HashingStrategyTest {
@Rule
public RunTestOnContext rule = new RunTestOnContext();
final String salt = Codec.base64Encode("keyboard.cat".getBytes(StandardCharsets.UTF_8));
@Test
public void testHashSimple() {
HashingStrategy strategy = HashingStrategy.load();
// should encode
String hash = strategy.hash("sha512", null, salt, "SuperSecret$!");
// should be valid
assertTrue(strategy.verify(hash, "SuperSecret$!"));
// should be wrong
assertFalse(strategy.verify(hash, "superSecret$!"));
}
@Test
public void testHashSHA1() {
HashingStrategy strategy = HashingStrategy.load();
assertNotNull(strategy.get("sha1"));
// should encode
String hash = strategy.hash("sha1", null, salt, "SuperSecret$!");
// should be valid
assertTrue(strategy.verify(hash, "SuperSecret$!"));
// should be wrong
assertFalse(strategy.verify(hash, "superSecret$!"));
}
@Test
public void testHashSHA256() {
HashingStrategy strategy = HashingStrategy.load();
assertNotNull(strategy.get("sha256"));
// should encode
String hash = strategy.hash("sha256", null, salt, "SuperSecret$!");
// should be valid
assertTrue(strategy.verify(hash, "SuperSecret$!"));
// should be wrong
assertFalse(strategy.verify(hash, "superSecret$!"));
}
@Test
public void testHashStronger() {
HashingStrategy strategy = HashingStrategy.load();
// should encode
String hash = strategy.hash("pbkdf2", null, salt, "SuperSecret$!");
// should be valid
assertTrue(strategy.verify(hash, "SuperSecret$!"));
// should be wrong
assertFalse(strategy.verify(hash, "superSecret$!"));
HashMap<String, String> params = new HashMap<>();
params.put("it", "100000");
String hashWithPararms = strategy.hash("pbkdf2", params, salt, "SuperSecret$!");
// should be different
assertNotEquals(hash, hashWithPararms);
// should be valid
assertTrue(strategy.verify(hash, "SuperSecret$!"));
// should be wrong
assertFalse(strategy.verify(hash, "superSecret$!"));
}
@Test
public void testHashBase64Verification() {
HashingStrategy strategy = HashingStrategy.load();
// base64 salts have _- characters instead pf /+
String salt = "QvcpO04_JYuwO-KvUhnCcPvcOvZp5oaJ9GFNfyHSYOA";
// should encode
String hash = strategy.hash("pbkdf2", null, salt, "SuperSecret$!");
// should be valid
assertTrue(strategy.verify(hash, "SuperSecret$!"));
}
}
```
|
Please help me generate a test for this class.
|
```package io.vertx.ext.auth;
import io.vertx.codegen.annotations.Fluent;
import io.vertx.codegen.annotations.VertxGen;
import io.vertx.ext.auth.impl.HashingStrategyImpl;
import java.util.Map;
import java.util.ServiceLoader;
/**
* Hashing Strategy manager.
* <p>
* This class will load system provided hashing strategies and algorithms.
*
* @author <a href="mailto:plopes@redhat.com">Paulo Lopes</a>
*/
@VertxGen
public interface HashingStrategy {
/**
* Factory method to load the algorithms from the system
*
* @return a Hashing Strategy capable of hashing using the available algorithms
*/
static HashingStrategy load() {
final HashingStrategyImpl strategy = new HashingStrategyImpl();
ServiceLoader<HashingAlgorithm> serviceLoader = ServiceLoader.load(HashingAlgorithm.class);
for (HashingAlgorithm algorithm : serviceLoader) {
strategy.add(algorithm);
}
return strategy;
}
/**
* Hashes a password.
*
* @param id the algorithm id
* @param params the algorithm specific parameters
* @param salt the given salt
* @param password the given password
* @return the hashed string
*/
String hash(String id, Map<String, String> params, String salt, String password);
/**
* Time constant password check. Regardless of the check, this algorithm executes the same number of
* checks regardless of the correctly number of characters
*
* @param hash the hash to verify
* @param password the password to test against
* @return boolean
*/
boolean verify(String hash, String password);
/**
* Get an algorithm interface by its Id
*
* @param id the algorithm id
* @return the algorithm
*/
HashingAlgorithm get(String id);
/**
* Put or replace an algorithm into the list of system loaded algorithms.
*
* @param id the algorithm id
* @param algorithm the implementation
* @return self
*/
@Fluent
HashingStrategy put(String id, HashingAlgorithm algorithm);
}
```
|
```package io.vertx.ext.auth.impl.jose;
import io.vertx.ext.auth.PubSecKeyOptions;
import org.junit.Test;
import static junit.framework.TestCase.assertFalse;
import static org.junit.Assert.assertNotNull;
/**
* @author <a href="mailto:david@davidafsilva.pt">david</a>
*/
public class CryptoTest {
@Test
public void ecdsaSignatureComplianceTest() throws Exception {
JWT jwt = new JWT()
.addJWK(new JWK(
new PubSecKeyOptions()
.setAlgorithm("ES512")
.setBuffer("-----BEGIN PUBLIC KEY-----\nMIGbMBAGByqGSM49AgEGBSuBBAAjA4GGAAQASisgweVL1tAtIvfmpoqvdXF8sPKTV9YTKNxBwkdkm+/auh4pR8TbaIfsEzcsGUVv61DFNFXb0ozJfurQ59G2XcgAn3vROlSSnpbIvuhKrzL5jwWDTaYa5tVF1Zjwia/5HUhKBkcPuWGXg05nMjWhZfCuEetzMLoGcHmtvabugFrqsAg=\n-----END PUBLIC KEY-----\n")));
assertFalse(jwt.isUnsecure());
//Test verification for token created using https://github.com/auth0/node-jsonwebtoken/tree/v7.0.1
assertNotNull(jwt.decode("eyJhbGciOiJFUzUxMiIsInR5cCI6IkpXVCJ9.eyJ0ZXN0IjoidGVzdCIsImlhdCI6MTQ2NzA2NTgyN30.Aab4x7HNRzetjgZ88AMGdYV2Ml7kzFbl8Ql2zXvBores7iRqm2nK6810ANpVo5okhHa82MQf2Q_Zn4tFyLDR9z4GAcKFdcAtopxq1h8X58qBWgNOc0Bn40SsgUc8wOX4rFohUCzEtnUREePsvc9EfXjjAH78WD2nq4tn-N94vf14SncQ"));
//Test verification for token created using https://github.com/jwt/ruby-jwt/tree/v1.5.4
assertNotNull(jwt.decode("eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzUxMiJ9.eyJ0ZXN0IjoidGVzdCJ9.AV26tERbSEwcoDGshneZmhokg-tAKUk0uQBoHBohveEd51D5f6EIs6cskkgwtfzs4qAGfx2rYxqQXr7LTXCNquKiAJNkTIKVddbPfped3_TQtmHZTmMNiqmWjiFj7Y9eTPMMRRu26w4gD1a8EQcBF-7UGgeH4L_1CwHJWAXGbtu7uMUn"));
}
}
```
|
Please help me generate a test for this class.
|
```package io.vertx.ext.auth.htpasswd.impl.hash;
import io.vertx.ext.auth.HashString;
import io.vertx.ext.auth.HashingAlgorithm;
import org.apache.commons.codec.digest.UnixCrypt;
/**
* Implementation of the Crypt Hashing algorithm
*
* @author <a href="mailto:plopes@redhat.com">Paulo Lopes</a>
*/
public class Crypt implements HashingAlgorithm {
@Override
public String id() {
return "";
}
@Override
public String hash(HashString hashString, String password) {
// htpasswd uses the first 2 bytes as salt
final String cryptSalt = hashString.hash().substring(0, 2);
return UnixCrypt.crypt(password, cryptSalt);
}
}
```
|
```package io.vertx.ext.auth.authorization.impl;
import io.vertx.core.MultiMap;
import org.junit.Test;
import static org.junit.Assert.*;
public class VariableAwareExpressionTest {
@Test
public void test() {
VariableAwareExpression expression = new VariableAwareExpression("foo");
String resolved = expression.resolve(MultiMap.caseInsensitiveMultiMap().add("foo", "bar"));
assertEquals("foo", resolved);
}
@Test
public void test1() {
VariableAwareExpression expression = new VariableAwareExpression("{foo}");
String resolved = expression.resolve(MultiMap.caseInsensitiveMultiMap().add("foo", "bar"));
assertEquals("bar", resolved);
}
}
```
|
Please help me generate a test for this class.
|
```package io.vertx.ext.auth.authorization.impl;
import io.vertx.core.MultiMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
class VariableAwareExpression {
private final String value;
private final transient Function<MultiMap, String>[] parts;
private transient boolean hasVariable = false;
@SuppressWarnings("unchecked")
public VariableAwareExpression(String value) {
this.value = Objects.requireNonNull(value).trim();
List<Function<MultiMap, String>> tmpParts = new ArrayList<>();
int currentPos = 0;
while (currentPos != -1) {
int openingCurlyBracePos = value.indexOf("{", currentPos);
if (openingCurlyBracePos == -1) {
if (currentPos < value.length()) {
String authorizationPart = value.substring(currentPos, value.length() - currentPos);
tmpParts.add(ctx -> authorizationPart);
}
break;
} else {
if (openingCurlyBracePos > currentPos) {
String authorizationPart = value.substring(currentPos, openingCurlyBracePos);
tmpParts.add(ctx -> authorizationPart);
}
int closingCurlyBracePos = value.indexOf("}", currentPos + 1);
if (closingCurlyBracePos == -1) {
throw new IllegalArgumentException("opening '{' without corresponding closing '}'");
} else if (closingCurlyBracePos - openingCurlyBracePos == 1) {
throw new IllegalArgumentException("empty '{}' is not allowed");
} else {
String part = value.substring(openingCurlyBracePos, closingCurlyBracePos + 1);
String variableName = value.substring(openingCurlyBracePos + 1, closingCurlyBracePos);
hasVariable = true;
tmpParts.add(ctx -> {
// substitute parameter
String result = ctx.get(variableName);
if (result != null) {
return result;
}
return part;
});
currentPos = closingCurlyBracePos + 1;
}
}
}
this.parts = new Function[tmpParts.size()];
for (int i = 0; i < tmpParts.size(); i++) {
this.parts[i] = tmpParts.get(i);
}
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof VariableAwareExpression))
return false;
VariableAwareExpression other = (VariableAwareExpression) obj;
return Objects.equals(value, other.value);
}
public boolean hasVariable() {
return hasVariable;
}
public String getValue() {
return value;
}
@Override
public int hashCode() {
return Objects.hash(value);
}
public String resolve(MultiMap context) {
// shortcut if there is no variable
if (!hasVariable) {
return value;
}
if (parts.length == 1) {
return parts[0].apply(context);
} else if (parts.length > 1) {
StringBuilder result = new StringBuilder();
for (Function<MultiMap, String> part : parts) {
result.append(part.apply(context));
}
return result.toString();
}
// should only happen when the length is 0
return "";
}
}
```
|
```package io.vertx.ext.auth;
import io.vertx.ext.auth.authorization.NotAuthorization;
import io.vertx.ext.auth.authorization.PermissionBasedAuthorization;
import org.junit.Assert;
import org.junit.Test;
public class NotAuthorizationTest {
@Test
public void testImpliesOk1() {
Assert.assertEquals(true, NotAuthorization.create(PermissionBasedAuthorization.create("p1"))
.verify(NotAuthorization.create(PermissionBasedAuthorization.create("p1"))));
}
@Test
public void testImpliesKo1() {
Assert.assertEquals(false, NotAuthorization.create(PermissionBasedAuthorization.create("p1"))
.verify(NotAuthorization.create(PermissionBasedAuthorization.create("p2"))));
}
@Test
public void testImpliesKo2() {
Assert.assertEquals(false, NotAuthorization.create(PermissionBasedAuthorization.create("p1"))
.verify(PermissionBasedAuthorization.create("p2")));
}
}
```
|
Please help me generate a test for this class.
|
```package io.vertx.ext.auth.authorization;
import io.vertx.codegen.annotations.VertxGen;
import io.vertx.ext.auth.authorization.impl.NotAuthorizationImpl;
/**
* Allows to perform a logical 'not' of the specified authorization
*
* @author <a href="mailto:stephane.bastian.dev@gmail.com">Stephane Bastian</a>
*/
@VertxGen
public interface NotAuthorization extends Authorization {
static NotAuthorization create(Authorization authorization) {
return new NotAuthorizationImpl(authorization);
}
Authorization getAuthorization();
}
```
|
```package io.vertx.ext.auth.webauthn.impl.attestation.tpm;
import io.vertx.core.buffer.Buffer;
public class CertInfo {
public static final long TPM_GENERATED = 0xFF544347L;
/**
* a special four byte constant stating that this is TPM generated structure.
* Must be set to TPM_GENERATED(0xFF544347)
*/
private final long magic;
/**
* algorithm used for attestation
*/
private final int type;
/**
* a name of a parent entity. Ignore
*/
private final byte[] qualifiedSigner;
/**
* contains hash of the attsToBeSigned.
* The hashing algorithm is specified by the “alg” field
*/
private final byte[] extraData;
/**
* contains information about TPP clock state.
* Clock, resetCount, restartCount and safe fields. Ignore
*/
private final byte[] clockInfo;
/**
* TPM-vendor-specific value identifying the version number of the firmware
*/
private final byte[] firmwareVersion;
/**
* a concatenation of hashing algorithm identifier and the hash of the pubArea.
* More in verification section
*/
private final byte[] attestedName;
/**
* Synthetic value from the first 2 bytes from attestedName
*/
private final int nameAlg;
/**
* Ignore
*/
private final byte[] qualifiedName;
public CertInfo(byte[] data) {
this(Buffer.buffer(data));
}
public CertInfo(Buffer certBuffer) {
int pos = 0;
int len;
// Get a magic constant
magic = certBuffer.getUnsignedInt(pos);
pos += 4;
// Determine the algorithm used for attestation
type = certBuffer.getUnsignedShort(pos);
pos += 2;
// The name of a parent entity, can be ignored
len = certBuffer.getUnsignedShort(pos);
pos += 2;
qualifiedSigner = certBuffer.getBytes(pos, pos + len);
pos += len;
// Get the expected hash of `attsToBeSigned`
len = certBuffer.getUnsignedShort(pos);
pos += 2;
extraData = certBuffer.getBytes(pos, pos + len);
pos += len;
// Information about the TPM device's internal clock, can be ignored
clockInfo = certBuffer.getBytes(pos, pos + 17);
pos += 17;
// TPM device firmware version
firmwareVersion = certBuffer.getBytes(pos, pos + 8);
pos += 8;
// Attested Name
len = certBuffer.getUnsignedShort(pos);
pos += 2;
attestedName = certBuffer.getBytes(pos, pos + len);
nameAlg = certBuffer.getUnsignedShort(pos);
pos += len;
// Attested qualified name, can be ignored
len = certBuffer.getUnsignedShort(pos);
pos += 2;
qualifiedName = certBuffer.getBytes(pos, pos + len);
}
public long getMagic() {
return magic;
}
public int getType() {
return type;
}
public byte[] getQualifiedSigner() {
return qualifiedSigner;
}
public byte[] getExtraData() {
return extraData;
}
public byte[] getClockInfo() {
return clockInfo;
}
public byte[] getFirmwareVersion() {
return firmwareVersion;
}
public byte[] getAttestedName() {
return attestedName;
}
public byte[] getQualifiedName() {
return qualifiedName;
}
public int getNameAlg() {
return nameAlg;
}
}
```
|
Please help me generate a test for this class.
|
```package io.vertx.ext.auth.impl;
import io.vertx.codegen.annotations.Nullable;
import io.vertx.core.impl.logging.Logger;
import io.vertx.core.impl.logging.LoggerFactory;
import javax.naming.InvalidNameException;
import javax.naming.ldap.LdapName;
import javax.security.auth.x500.X500Principal;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SignatureException;
import java.security.cert.CertificateException;
import java.security.cert.X509CRL;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public final class CertificateHelper {
private static final Logger LOG = LoggerFactory.getLogger(CertificateHelper.class);
public final static class CertInfo {
private final Map<String, String> subject;
private final int version;
private final int basicConstraintsCA;
private CertInfo(Map<String, String> subject, int version, int basicConstraintsCA) {
this.subject = subject;
this.version = version;
this.basicConstraintsCA = basicConstraintsCA;
}
public boolean subjectHas(String key) {
if (subject != null) {
return subject.containsKey(key);
}
return false;
}
public @Nullable String subject(String key) {
if (subject != null) {
return subject.get(key);
}
return null;
}
public int version() {
return version;
}
public int basicConstraintsCA() {
return basicConstraintsCA;
}
public boolean isEmpty() {
if (subject != null) {
return subject.isEmpty();
} else {
return true;
}
}
}
private CertificateHelper() {
}
public static void checkValidity(List<X509Certificate> certificates, List<X509CRL> crls) throws CertificateException, NoSuchAlgorithmException, InvalidKeyException, SignatureException, NoSuchProviderException {
checkValidity(certificates, true, crls);
}
public static void checkValidity(List<X509Certificate> certificates, boolean withRootCA, List<X509CRL> crls) throws CertificateException, NoSuchAlgorithmException, InvalidKeyException, SignatureException, NoSuchProviderException {
if (certificates == null || certificates.size() == 0) {
throw new CertificateException("empty chain");
}
final long now = System.currentTimeMillis();
for (int i = 0; i < certificates.size(); i++) {
final X509Certificate subjectCert = certificates.get(i);
subjectCert.checkValidity();
// check if the certificate is revoked
if (crls != null) {
for (X509CRL crl : crls) {
if (crl.getNextUpdate().getTime() < now) {
LOG.warn("CRL is out of date nextUpdate < now");
}
if (crl.isRevoked(subjectCert)) {
throw new CertificateException("Certificate is revoked");
}
}
}
// single certificate nothing else to be checked
if (certificates.size() == 1) {
return;
}
final X509Certificate issuerCert;
if (i + 1 < certificates.size()) {
issuerCert = certificates.get(i + 1);
// verify that the issuer matches the next one in the list
if (!subjectCert.getIssuerX500Principal().equals(issuerCert.getSubjectX500Principal())) {
throw new CertificateException("Certificate path issuers dont match: [" + subjectCert.getIssuerX500Principal() + "] != [" + issuerCert.getSubjectX500Principal() + "]");
}
// verify the certificate against the issuer
subjectCert.verify(issuerCert.getPublicKey());
}
}
if (withRootCA) {
// the last certificate should be self signed
X509Certificate root = certificates.get(certificates.size() - 1);
root.verify(root.getPublicKey());
}
}
public static CertInfo getCertInfo(X509Certificate cert) {
final String subject = cert.getSubjectX500Principal().getName(X500Principal.RFC2253);
Map<String, String> sub = null;
if (subject != null && !"".equals(subject)) {
try {
LdapName rfc2253 = new LdapName(subject);
sub = new HashMap<>();
for (int i = 0; i < rfc2253.size(); i++) {
String value = rfc2253.get(i);
int idx = value.indexOf('=');
if (idx != -1) {
sub.put(value.substring(0, idx), value.substring(idx + 1));
} else {
sub.put(value, null);
}
}
} catch (InvalidNameException e) {
// this isn't parseable, so ignore
}
}
return new CertInfo(sub, cert.getVersion(), cert.getBasicConstraints());
}
}
```
|
```package cn.lite.flow.console.job;
import cn.lite.flow.console.kernel.job.VersionDailyInit2FireJob;
import cn.lite.flow.console.test.BaseTest;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
/**
* Created by ly on 2019/1/4.
*/
public class VersionDailyInit2FireJobTest extends BaseTest {
@Autowired
private VersionDailyInit2FireJob versionDailyInit2FireJob;
@Test
public void test() {
versionDailyInit2FireJob.execute();
}
}
```
|
Please help me generate a test for this class.
|
```package cn.lite.flow.console.kernel.job;
import cn.lite.flow.common.job.basic.AbstractUnstatefullJob;
import cn.lite.flow.common.model.query.Page;
import cn.lite.flow.common.utils.ExceptionUtils;
import cn.lite.flow.common.time.TimeCalculatorFactory;
import cn.lite.flow.common.utils.DateUtils;
import cn.lite.flow.console.model.basic.Task;
import cn.lite.flow.console.model.basic.TaskVersionDailyInit;
import cn.lite.flow.console.model.consts.DailyInitStatus;
import cn.lite.flow.console.model.consts.TaskStatus;
import cn.lite.flow.console.model.query.TaskVersionDailyInitQM;
import cn.lite.flow.console.service.TaskService;
import cn.lite.flow.console.service.TaskVersionDailyInitService;
import cn.lite.flow.console.service.TaskVersionService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @description: 初始化相关job
* @author: yueyunyue
* @create: 2018-07-30
**/
public class VersionDailyInit2FireJob extends AbstractUnstatefullJob {
@Autowired
private TaskService taskService;
@Autowired
private TaskVersionDailyInitService dailyInitService;
@Autowired
private TaskVersionService versionService;
private final static int PAGE_SIZE = 100;
private final static int CONCURRENT_COUNT = 10;
@Override
public void executeInternal() {
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(CONCURRENT_COUNT);
TaskVersionDailyInitQM dailyInitQM = new TaskVersionDailyInitQM();
dailyInitQM.setStatus(DailyInitStatus.NEW.getValue());
dailyInitQM.addOrderAsc(TaskVersionDailyInitQM.COL_ID);
List<TaskVersionDailyInit> dailyInits = null;
final int pageNo = 1;
do{
try {
dailyInitQM.setPage(Page.getPageByPageNo(pageNo, PAGE_SIZE));
dailyInits = dailyInitService.list(dailyInitQM);
if(CollectionUtils.isEmpty(dailyInits)){
break;
}
final CountDownLatch countDownLatch = new CountDownLatch(dailyInits.size());
for(TaskVersionDailyInit dailyInit : dailyInits){
//已添加的,忽略
Long taskId = dailyInit.getTaskId();
fixedThreadPool.execute(() -> {
try {
Task task = taskService.getById(taskId);
if(task.getStatus() != TaskStatus.ONLINE.getValue()){
dailyInitService.failDailyInit(dailyInit.getId(), "task is not online,info:" + task.toString());
return;
}
/**
* 生成任务版本
*/
Date day = DateUtils.longToDate(dailyInit.getDay());
Date startTime = DateUtils.getStartTimeOfDay(day);
Date endTime = DateUtils.getEndTimeOfDay(day);
versionService.calVersionAndInstanceWithDependency(taskId, startTime, endTime);
dailyInitService.successDailyInit(dailyInit.getId());
LOG.info("daily init of task:{}", taskId);
}catch (Throwable e){
String errorMsg = ExceptionUtils.collectStackMsg(e);
dailyInitService.failDailyInit(dailyInit.getId(), errorMsg);
LOG.info("daily init error of task:{}", taskId, e);
}finally {
countDownLatch.countDown();
}
});
}
countDownLatch.await();
}catch (Throwable e){
LOG.error("daily init error", e);
}
}while (CollectionUtils.isNotEmpty(dailyInits));
}
}
```
|
```package cn.lite.flow.executor.test.container;
import cn.lite.flow.common.model.consts.CommonConstants;
import cn.lite.flow.executor.common.consts.Constants;
import cn.lite.flow.executor.kernel.container.ContainerFactory;
import cn.lite.flow.executor.kernel.container.impl.ShellContainer;
import cn.lite.flow.executor.model.basic.ExecutorJob;
import cn.lite.flow.executor.model.consts.ExecutorJobStatus;
import cn.lite.flow.executor.model.kernel.Container;
import cn.lite.flow.executor.service.ExecutorContainerService;
import cn.lite.flow.executor.service.ExecutorJobService;
import cn.lite.flow.executor.test.base.BaseTest;
import com.alibaba.fastjson.JSONObject;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
/**
* @description: 容器测试
* @author: yueyunyue
* @create: 2019-01-27
**/
public class ShellContainerTest extends BaseTest {
@Autowired
private ExecutorContainerService containerService;
@Autowired
private ExecutorJobService jobService;
@Test
public void testShell() throws Exception {
JSONObject param = new JSONObject();
param.put(Constants.SHELL_COINTENT, "touch /tmp/123.log");
param.put(CommonConstants.PARAM_EXECUTOR_JOB_NAME, "shell");
ExecutorJob job = new ExecutorJob();
job.setId(1l);
job.setConfig(param.toJSONString());
job.setStatus(ExecutorJobStatus.NEW.getValue());
ShellContainer shellContainer = new ShellContainer(job);
shellContainer.run();
}
}
```
|
Please help me generate a test for this class.
|
```package cn.lite.flow.executor.kernel.container.impl;
import cn.lite.flow.common.model.consts.CommonConstants;
import cn.lite.flow.common.utils.FreeMarkerUtils;
import cn.lite.flow.common.utils.ParamExpressionUtils;
import cn.lite.flow.common.utils.ParamUtils;
import cn.lite.flow.executor.common.consts.Constants;
import cn.lite.flow.executor.common.exception.ExecutorRuntimeException;
import cn.lite.flow.executor.common.utils.ExecutorLoggerFactory;
import cn.lite.flow.executor.common.utils.Props;
import cn.lite.flow.executor.kernel.conf.ExecutorMetadata;
import cn.lite.flow.executor.kernel.job.ShellProcessJob;
import cn.lite.flow.executor.kernel.utils.JobUtils;
import cn.lite.flow.executor.model.basic.ExecutorJob;
import cn.lite.flow.executor.model.kernel.SyncContainer;
import cn.lite.flow.executor.service.ExecutorJobService;
import cn.lite.flow.executor.service.utils.ExecutorFileUtils;
import cn.lite.flow.executor.service.utils.ExecutorServiceUtils;
import com.google.common.collect.Maps;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.Map;
/**
* @description: java进程容器
* @author: yueyunyue
* @create: 2018-08-17
**/
public class ShellContainer extends SyncContainer {
private ShellProcessJob shellProcessJob;
private final static Logger LOG = LoggerFactory.getLogger(ShellContainer.class);
public ShellContainer(ExecutorJob executorJob) {
super(executorJob);
}
@Override
public void runInternal() throws Exception {
try {
String config = executorJob.getConfig();
Props sysProps = new Props();
Props props = new Props(config);
String jobWorkspace = JobUtils.getWorkspace(executorJob);
Logger logger = JobUtils.getLogger(executorJob);
/**
* 生成脚本文件
*/
String filePath = props.getString(CommonConstants.PARAM_FILE);
String param = props.getString(CommonConstants.PARAM);
String shellName = Constants.SHELL_SCRIPT_PREFIX + executorJob.getId() + CommonConstants.POINT + Constants.SHELL_COMMAND;
String shellPath = jobWorkspace + CommonConstants.FILE_SPLIT + shellName;
Map<String, String> jobParamMap = props.getParamMap();
Map<String, String> paramMap = Maps.newHashMap();
paramMap.putAll(jobParamMap);
try {
/**
* 1.如果已经传了shell内容,直接使用;
* 2.通过附件上传的需要把内容拿下来
*/
String shellContent = props.getString(CommonConstants.PARAM_CONTENT);
if(StringUtils.isBlank(shellContent)){
shellContent = ExecutorFileUtils.getFileContent(filePath);
}
logger.info("job:{} get origin shell content:{}", executorJob.getId(), shellContent);
/**
* 参数不为空,替换关键字
*/
if(StringUtils.isNotBlank(param)){
paramMap.putAll(ParamUtils.param2Map(param));
}
shellContent = ParamExpressionUtils.handleParam(shellContent, paramMap);
logger.info("job:{} handle shell param:{} content:{}", executorJob.getId(), paramMap.toString(), shellContent);
FileUtils.write(new File(shellPath), shellContent);
props.put(Constants.SHELL_SCRIPT_PATH, shellPath);
} catch (Throwable e) {
logger.error("job: {} write shell script error", this.executorJob.getId(), e);
throw new ExecutorRuntimeException(e.getMessage());
}
this.shellProcessJob = new ShellProcessJob(executorJob.getId(), sysProps, props, logger);
shellProcessJob.run();
} finally {
}
}
@Override
public void kill() {
try {
shellProcessJob.cancel();
LOG.info("kill remote shell container executorJobId:{} get applicationId:{}", executorJob.getId(), executorJob.getApplicationId());
} catch (Throwable e) {
LOG.error("kill remote shell container, jobId:" + executorJob.getId(), e);
throw new ExecutorRuntimeException(e.getMessage());
}
}
@Override
public boolean isFailed() {
return shellProcessJob.isCanceled();
}
@Override
public boolean isSuccess() {
return shellProcessJob.isSuccess();
}
}
```
|
```package cn.lite.flow.console.job;
import cn.lite.flow.console.kernel.job.TaskVersionDailyInitJob;
import cn.lite.flow.console.test.BaseTest;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
/**
* Created by ly on 2019/1/4.
*/
public class TaskVersionDailyInitJobTest extends BaseTest {
@Autowired
private TaskVersionDailyInitJob taskVersionDailyInitJob;
@Test
public void test() {
taskVersionDailyInitJob.execute();
}
}
```
|
Please help me generate a test for this class.
|
```package cn.lite.flow.console.kernel.job;
import cn.lite.flow.common.job.basic.AbstractUnstatefullJob;
import cn.lite.flow.common.model.query.Page;
import cn.lite.flow.common.utils.DateUtils;
import cn.lite.flow.console.model.basic.Task;
import cn.lite.flow.console.model.basic.TaskVersionDailyInit;
import cn.lite.flow.console.model.consts.TaskStatus;
import cn.lite.flow.console.model.query.TaskQM;
import cn.lite.flow.console.service.TaskService;
import cn.lite.flow.console.service.TaskVersionDailyInitService;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.Date;
import java.util.List;
/**
* @description: 初始化相关job
* @author: yueyunyue
* @create: 2018-07-30
**/
public class TaskVersionDailyInitJob extends AbstractUnstatefullJob {
@Autowired
private TaskService taskService;
@Autowired
private TaskVersionDailyInitService dailyInitService;
private final static int PAGE_SIZE = 100;
@Override
public void executeInternal() {
Date tomorrowDate = DateUtils.getTomorrowDate();
long tomorrowLongDate = DateUtils.dateToLong(tomorrowDate);
TaskQM taskQM = new TaskQM();
taskQM.setStatus(TaskStatus.ONLINE.getValue());
taskQM.addOrderAsc(TaskQM.COL_ID);
List<Task> tasks = null;
int pageNo = 1;
do{
List<TaskVersionDailyInit> dailyInits = Lists.newArrayList();
taskQM.setPage(Page.getPageByPageNo(pageNo, PAGE_SIZE));
tasks = taskService.list(taskQM);
if(CollectionUtils.isEmpty(tasks)){
break;
}
for(Task task : tasks){
//已添加的,忽略
TaskVersionDailyInit taskDailyInit = dailyInitService.getTaskDailyInit(task.getId(), tomorrowLongDate);
if(taskDailyInit != null){
continue;
}
TaskVersionDailyInit dailyInit = new TaskVersionDailyInit();
dailyInit.setDay(tomorrowLongDate);
dailyInit.setTaskId(task.getId());
dailyInits.add(dailyInit);
LOG.info("init taskVersion of task:{}, info:{}", task.getId(), dailyInit.toString());
}
//批量添加
dailyInitService.batchAdd(dailyInits);
pageNo ++;
}while (CollectionUtils.isNotEmpty(tasks));
}
}
```
|
```package cn.lite.flow.console.job;
import cn.lite.flow.console.kernel.job.ConsumerEventQueueJob;
import cn.lite.flow.console.kernel.job.InstanceReady2FireJob;
import cn.lite.flow.console.test.BaseTest;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
/**
* Created by ly on 2019/1/4.
*/
public class InstanceReady2FireJobTest extends BaseTest {
@Autowired
private InstanceReady2FireJob instanceReady2FireJob;
@Autowired
private ConsumerEventQueueJob consumerEventQueueJob;
@Test
public void test() {
instanceReady2FireJob.execute();
consumerEventQueueJob.execute();
}
}
```
|
Please help me generate a test for this class.
|
```package cn.lite.flow.console.kernel.job;
import cn.lite.flow.common.job.basic.AbstractUnstatefullJob;
import cn.lite.flow.console.model.event.consts.Event;
import cn.lite.flow.console.model.event.model.ScheduleEvent;
import cn.lite.flow.console.service.queue.EventQueue;
import cn.lite.flow.console.service.TaskInstanceService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
/**
* @description: 初始化完成并且已经到达触发时间
* @author: yueyunyue
* @create: 2018-08-03
**/
public class InstanceReady2FireJob extends AbstractUnstatefullJob {
@Autowired
private TaskInstanceService instanceService;
@Override
public void executeInternal() {
List<Long> instanceIds = instanceService.listReady2RunInstance();
if(CollectionUtils.isNotEmpty(instanceIds)){
for(Long instanceId : instanceIds){
ScheduleEvent scheduleEvent = ScheduleEvent.newInstance(Event.READY, instanceId);
EventQueue.put(scheduleEvent);
}
}
}
}
```
|
```package cn.lite.flow.executor.test.container;
import cn.lite.flow.executor.kernel.container.ContainerFactory;
import cn.lite.flow.executor.model.basic.ExecutorJob;
import cn.lite.flow.executor.model.kernel.Container;
import cn.lite.flow.executor.service.ExecutorContainerService;
import cn.lite.flow.executor.service.ExecutorJobService;
import cn.lite.flow.executor.test.base.BaseTest;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
/**
* @description: 容器测试
* @author: yueyunyue
* @create: 2019-01-27
**/
public class ContainerTest extends BaseTest {
@Autowired
private ExecutorContainerService containerService;
@Autowired
private ExecutorJobService jobService;
@Test
public void testJavaProcess() throws Exception {
long jobId = 5L;
ExecutorJob executorJob = jobService.getById(jobId);
Container container = ContainerFactory.newInstance(executorJob);
container.run();
}
}
```
|
Please help me generate a test for this class.
|
```package cn.lite.flow.executor.model.kernel;
/**
* 基础container
*/
public interface Container {
/**
* 运行方法
* @throws Exception
*/
void run() throws Exception;
/**
* 取消任务
* @throws Exception
*/
void kill() throws Exception;
/**
* 任务是否已经取消
* @return
*/
boolean isFailed();
/**
* 是否已经成功
* @return
*/
boolean isSuccess();
/**
* 是否运行中
* @return
*/
boolean isRunning();
/**
* 是否最终状态
* @return
*/
boolean isFinish();
}
```
|
```package cn.lite.flow.executor.test.process;
import cn.lite.flow.executor.common.consts.Constants;
import cn.lite.flow.executor.common.utils.Props;
import cn.lite.flow.executor.kernel.job.JavaProcessJob;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @description:
* @author: yueyunyue
* @create: 2018-08-23
**/
public class JavaProcessTest {
private Logger logger = LoggerFactory.getLogger(JavaProcessTest.class);
@Test
public void testHello() throws Exception {
String mainClass = "cn.lite.flow.hello.word.HelloLiteFlow";
String jarPath = "/Users/yueyunyue/workspace4m/lite-flow/docs/jars";
String jvmArgs = "-Xmn256m -Xmx256m";
logger.info(mainClass);
Props props = new Props();
props.put(Constants.JAVA_MAIN_CLASS, mainClass);
// props.put(Constants.WORKING_DIR, jarPath);
props.put(Constants.JAVA_JVM_PARAMS, jvmArgs);
props.put(Constants.JAVA_MAIN_JAR_PATH, jarPath);
props.put(Constants.JAVA_MAIN_ARGS, jarPath + "/config.json");
Props sysProps = new Props();
JavaProcessJob javaProcessJob = new JavaProcessJob(0l,sysProps, props, logger);
javaProcessJob.run();
System.in.read();
}
}
```
|
Please help me generate a test for this class.
|
```package cn.lite.flow.executor.kernel.job;
import cn.lite.flow.common.model.consts.CommonConstants;
import cn.lite.flow.executor.common.consts.Constants;
import cn.lite.flow.executor.common.utils.Props;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* @description: Java 进程任务
* @author: yueyunyue
* @create: 2018-08-22
**/
public class JavaProcessJob extends ProcessJob {
public JavaProcessJob(long executorJobId, Props sysProps, Props jobProps, Logger log) {
super(executorJobId, sysProps, jobProps, log);
}
@Override
protected List<String> getCommandList() {
final ArrayList<String> list = new ArrayList<>();
list.add(this.createJavaCommandLine());
return list;
}
protected String createJavaCommandLine() {
StringBuilder command = new StringBuilder();
command.append(Constants.JAVA_COMMAND).append(CommonConstants.BLANK_SPACE);
command.append(this.getJVMArguments()).append(CommonConstants.BLANK_SPACE);
command.append(Constants.JAVA_COMMAND_CP).append(CommonConstants.BLANK_SPACE).append(this.createArguments(this.getClassPaths(), Constants.JAVA_CLASSPATH_SPLIT)).append(CommonConstants.BLANK_SPACE);
command.append(this.getJavaClass()).append(CommonConstants.BLANK_SPACE);
command.append(this.getMainArguments()).append(CommonConstants.BLANK_SPACE);
String commandStr = command.toString();
logger.info("create java command: " + commandStr);
return commandStr;
}
protected List<String> getClassPaths() {
final List<String> classPaths = jobProps.getStringList(Constants.JAVA_CLASSPATH, null, CommonConstants.COMMA);
final ArrayList<String> classpathList = new ArrayList<>();
/**
* 添加全局的classpath,一些通用的jar包
*/
if (jobProps.containsKey(Constants.JAVA_GLOBAL_CLASSPATH)) {
final List<String> globalClasspath =
jobProps.getStringList(Constants.JAVA_GLOBAL_CLASSPATH);
for (final String global : globalClasspath) {
logger.info("add to global classpath:" + global);
classpathList.add(global);
}
}
if (classPaths == null) {
String mainJarPath = getPath();
final File path = new File(mainJarPath);
logger.info("load jar path {}" ,path);
/**
* 1.文件夹,把所有jar都添加进来
* 2.如果是文件,并且是jar,直接添加
*/
if (path != null) {
if(path.isDirectory()){
for (final File file : path.listFiles()) {
if (StringUtils.endsWith(file.getName(), Constants.JAVA_JAR_SUFFIX)) {
String jarAbsolutePath = file.getAbsolutePath();
logger.info("add to classpath:" + jarAbsolutePath);
classpathList.add(jarAbsolutePath);
}
}
}else if(StringUtils.endsWith(path.getName(), Constants.JAVA_JAR_SUFFIX)) {
classpathList.add(path.getAbsolutePath());
}
}
} else {
classpathList.addAll(classPaths);
}
return classpathList;
}
protected String createArguments(final List<String> arguments, final String separator) {
if (arguments != null && arguments.size() > 0) {
String param = "";
for (final String arg : arguments) {
param += arg + separator;
}
return param.substring(0, param.length() - 1);
}
return "";
}
protected String getJavaClass() {
return jobProps.getString(Constants.JAVA_MAIN_CLASS);
}
/**
* 获取jvm堆最小数
* @return
*/
protected String getInitialMemorySize() {
return jobProps.getString(Constants.JAVA_INITIAL_MEMORY_SIZE,
Constants.JAVA_DEFAULT_INITIAL_MEMORY_SIZE);
}
protected String getMaxMemorySize() {
return jobProps.getString(Constants.JAVA_MAX_MEMORY_SIZE, Constants.JAVA_DEFAULT_MAX_MEMORY_SIZE);
}
/**
* 获取运行参数
* @return
*/
protected String getMainArguments() {
return jobProps.getString(Constants.JAVA_MAIN_ARGS, "");
}
/**
* 获取jvm参数
* @return
*/
protected String getJVMArguments() {
final String globalJVMArgs = jobProps.getString(Constants.JAVA_GLOBAL_JVM_PARAMS, null);
if (globalJVMArgs == null) {
return jobProps.getString(Constants.JAVA_JVM_PARAMS, "");
}
return globalJVMArgs + CommonConstants.BLANK_SPACE + jobProps.getString(Constants.JAVA_JVM_PARAMS, "");
}
/**
* 获取main函数所在jar的路径
* @return
*/
private String getPath(){
String mainJarPath = jobProps.getString(Constants.JAVA_MAIN_JAR_PATH, "");
return mainJarPath;
}
}
```
|
```package ch.securify.patterns;
import org.junit.Test;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
public class RepeatedCallTest {
@Test
public void isSafe() throws IOException {
String hexViolation = "src/test/resources/solidity/repeated-calls-tn.bin.hex";
HelperInstructionPattern helperInstructionPattern = new HelperInstructionPattern(hexViolation, new RepeatedCall());
assertEquals(0, helperInstructionPattern.pattern.violations.size());
assertEquals(0, helperInstructionPattern.pattern.warnings.size());
assertEquals(1, helperInstructionPattern.pattern.safe.size());
}
@Test
public void isSafe2() throws IOException {
String hexViolation = "src/test/resources/solidity/repeated-calls-tn2.bin.hex";
HelperInstructionPattern helperInstructionPattern = new HelperInstructionPattern(hexViolation, new RepeatedCall());
assertEquals(0, helperInstructionPattern.pattern.violations.size());
assertEquals(0, helperInstructionPattern.pattern.warnings.size());
assertEquals(2, helperInstructionPattern.pattern.safe.size());
}
@Test
public void isViolation() throws IOException {
String hexViolation = "src/test/resources/solidity/repeated-calls-tp.bin.hex";
HelperInstructionPattern helperInstructionPattern = new HelperInstructionPattern(hexViolation, new RepeatedCall());
assertEquals(1, helperInstructionPattern.pattern.violations.size());
assertEquals(0, helperInstructionPattern.pattern.warnings.size());
assertEquals(1, helperInstructionPattern.pattern.safe.size());
}
}
```
|
Please help me generate a test for this class.
|
```package ch.securify.patterns;
import ch.securify.analysis.AbstractDataflow;
import ch.securify.analysis.Status;
import ch.securify.decompiler.Variable;
import ch.securify.decompiler.instructions.*;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class RepeatedCall extends AbstractInstructionPattern {
public RepeatedCall() {
super(new PatternDescription("RepeatedCall",
RepeatedCall.class,
"Repeated call to an untrusted contract",
"Repeated call to an untrusted contract may result in different values",
PatternDescription.Severity.High,
PatternDescription.Type.Security));
}
@Override
protected boolean applicable(Instruction instr, AbstractDataflow dataflow) {
if (!(instr instanceof CallingInstruction))
return false;
CallingInstruction call = (CallingInstruction) instr;
if (call.isBuiltInContractCall()) {
return false;
}
Variable gasAmount = call.getInput()[0];
return !gasAmount.hasConstantValue() || AbstractDataflow.getInt(gasAmount.getConstantValue()) != 0;
}
@Override
protected boolean isViolation(Instruction instr, List<Instruction> methodInstructions, List<Instruction> contractInstructions, AbstractDataflow dataflow) {
return isViolation((CallingInstruction) instr, methodInstructions, dataflow);
}
protected boolean isViolation(CallingInstruction instr, List<Instruction> methodInstructions, AbstractDataflow dataflow) {
Variable callee = instr.getInput()[1];
// If the code is from a safe source it should be fine
if (dataflow.varMayDepOn(instr, callee, CallDataLoad.class) != Status.SATISFIABLE && dataflow.varMayDepOn(instr, callee, CallDataCopy.class) != Status.SATISFIABLE) {
return false;
}
Instruction prev = instr.getPrev();
for (Instruction mInstr : methodInstructions) {
if (!mInstr.getClass().equals(instr.getClass()))
continue;
CallingInstruction call = (CallingInstruction) mInstr;
Variable targetCall = call.getInput()[1];
Variable targetInstr = instr.getInput()[1];
if (targetCall.hasConstantValue() != targetInstr.hasConstantValue())
continue;
if (call.getMemoryInputs().size() != instr.getMemoryInputs().size())
continue;
if (call == instr) {
// Check if it can be reached through a loop
if (dataflow.mayFollow(call, prev) != Status.SATISFIABLE)
continue;
} else {
// Check if the two operations are subsequent
if (dataflow.mustPrecede(call, instr) != Status.SATISFIABLE)
continue;
}
// Only consider calls to untrusted code
if (targetInstr.hasConstantValue()) {
continue;
}
Iterator<Variable> callMemory = call.getMemoryInputs().iterator();
Iterator<Variable> instrMemory = instr.getMemoryInputs().iterator();
// Skip if one has no memory info
if (callMemory.hasNext() != instrMemory.hasNext()) {
continue;
}
// In case of no memory info at least check the length
if (!instrMemory.hasNext()) {
Variable callMemorySize = call.getInput()[call.getInputMemorySize()];
Variable instrMemorySize = instr.getInput()[instr.getInputMemorySize()];
if (callMemorySize.hasConstantValue() != instrMemorySize.hasConstantValue()) {
continue;
}
if ((callMemorySize.hasConstantValue()) && (Arrays.equals(callMemorySize.getConstantValue(), instrMemorySize.getConstantValue()))) {
continue;
}
}
boolean matched = true;
while (instrMemory.hasNext()) {
Variable callMemoryVar = callMemory.next();
Variable instrMemoryVar = instrMemory.next();
if (callMemoryVar.hasConstantValue() != instrMemoryVar.hasConstantValue()) {
matched = false;
break;
}
if (callMemoryVar.hasConstantValue() && instrMemoryVar.hasConstantValue()) {
if (!Arrays.equals(callMemoryVar.getConstantValue(), instrMemoryVar.getConstantValue())) {
matched = false;
break;
}
}
}
// More Memory left for call
if (callMemory.hasNext()) {
continue;
}
if (matched) {
return true;
}
}
return false;
}
@Override
protected boolean isCompliant(Instruction instr, List<Instruction> methodInstructions, List<Instruction> contractInstructions, AbstractDataflow dataflow) {
return isCompliant((CallingInstruction) instr, methodInstructions, dataflow);
}
protected boolean isCompliant(CallingInstruction instr, List<Instruction> methodInstructions, AbstractDataflow dataflow) {
Variable callee = instr.getInput()[1];
// If the code is from a safe source it should be fine
if (dataflow.varMayDepOn(instr, callee, CallDataLoad.class) == Status.UNSATISFIABLE && dataflow.varMayDepOn(instr, callee, CallDataCopy.class) == Status.UNSATISFIABLE) {
return true;
}
Instruction prev = instr.getPrev();
for (Instruction mInstr : methodInstructions) {
if (mInstr == instr) {
// Check if it can be reached through a loop
if (dataflow.mayFollow(mInstr, prev) == Status.UNSATISFIABLE)
continue;
} else {
// Check if the two operations are subsequent
if (dataflow.mayFollow(mInstr, instr) == Status.UNSATISFIABLE)
continue;
}
if (!mInstr.getClass().equals(instr.getClass()))
continue;
CallingInstruction call = (CallingInstruction) mInstr;
Variable targetCall = call.getInput()[1];
// Trusted code is considered safe
if (targetCall.hasConstantValue()) {
continue;
}
Variable targetInstr = instr.getInput()[1];
if (targetCall.hasConstantValue() != targetInstr.hasConstantValue())
continue;
if (call.getMemoryInputs().size() != instr.getMemoryInputs().size())
continue;
Iterator<Variable> callMemory = call.getMemoryInputs().iterator();
Iterator<Variable> instrMemory = instr.getMemoryInputs().iterator();
// In case of no memory info at least check the length
if (!instrMemory.hasNext()) {
Variable callMemorySize = call.getInput()[call.getInputMemorySize()];
Variable instrMemorySize = instr.getInput()[instr.getInputMemorySize()];
if (callMemorySize.hasConstantValue() != instrMemorySize.hasConstantValue()) {
continue;
}
if ((callMemorySize.hasConstantValue()) && (Arrays.equals(callMemorySize.getConstantValue(), instrMemorySize.getConstantValue()))) {
continue;
}
}
boolean matched = true;
while (instrMemory.hasNext()) {
Variable callMemoryVar = callMemory.next();
Variable instrMemoryVar = instrMemory.next();
if (callMemoryVar.hasConstantValue() != instrMemoryVar.hasConstantValue()) {
matched = false;
break;
}
if (callMemoryVar.hasConstantValue() && instrMemoryVar.hasConstantValue()) {
if (!Arrays.equals(callMemoryVar.getConstantValue(), instrMemoryVar.getConstantValue())) {
matched = false;
break;
}
}
}
if (matched) {
return false;
}
}
return true;
}
}
```
|
```package ch.securify;
import junit.framework.TestCase;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.TreeMap;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import static ch.securify.Main.processSolidityFile;
public class DecompilationBugTest {
@Test
public void testFirstExample() throws IOException, InterruptedException {
processWithoutException("src/test/resources/solidity/decompile.sol");
}
private void processWithoutException(String filesol) throws IOException, InterruptedException {
File tmpFile = File.createTempFile("solc-0.5", "");
String tmpPath = tmpFile.getPath();
URL website = new URL("https://github.com/ethereum/solidity/releases/download/v0.5.0/solc-static-linux");
try (InputStream in = website.openStream()) {
Files.copy(in, tmpFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
File f = new File(tmpPath);
f.setExecutable(true, true);
String livestatusfile = File.createTempFile("securify_livestatusfile", "").getPath();
TreeMap<String, SolidityResult> output = processSolidityFile(tmpPath, filesol, livestatusfile);
output.values().forEach(s -> TestCase.assertTrue(s.securifyErrors.isEmpty()));
}
}
```
|
Please help me generate a test for this class.
|
```package ch.securify.decompiler.instructions;
public class Gt extends Instruction {
@Override
public String getStringRepresentation() {
return getOutput()[0] + " = (" + getInput()[0] + " > " + getInput()[1] + ")";
}
}
```
|
```package ch.securify.patterns;
import org.junit.Test;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
public class TODReceiverTest {
@Test
public void isViolation() throws IOException {
String hexViolation = "src/test/resources/solidity/TODReceiver.bin.hex";
HelperInstructionPattern helperInstructionPattern = new HelperInstructionPattern(hexViolation, new TODReceiver());
assertEquals(1, helperInstructionPattern.pattern.violations.size());
}
}```
|
Please help me generate a test for this class.
|
```package ch.securify.patterns;
import ch.securify.analysis.AbstractDataflow;
import ch.securify.analysis.Dataflow;
import ch.securify.analysis.Status;
import ch.securify.decompiler.Variable;
import ch.securify.decompiler.instructions.*;
import java.util.List;
public class TODReceiver extends AbstractInstructionPattern {
public TODReceiver() {
super(new PatternDescription("TransactionReordering",
TODReceiver.class,
"Transaction Order Affects Ether Receiver",
"The receiver of ether transfers must not be influenced by other transactions.",
PatternDescription.Severity.Critical,
PatternDescription.Type.Security));
}
@Override
protected boolean applicable(Instruction instr, AbstractDataflow dataflow) {
if (!(instr instanceof Call) || ((Call) instr).isBuiltInContractCall())
return false;
Variable value = instr.getInput()[2];
if (value.hasConstantValue() && AbstractDataflow.getInt(value.getConstantValue()) == 0)
return false;
return true;
}
@Override
protected boolean isViolation(Instruction call, List<Instruction> methodInstructions, List<Instruction> contractInstructions, AbstractDataflow dataflow) {
assert (call instanceof Call);
Variable receiver = call.getInput()[1];
if (dataflow.varMustDepOn(call, receiver, SLoad.class) == Status.SATISFIABLE) {
for (Instruction sstore : contractInstructions) {
if (!(sstore instanceof SStore))
continue;
Variable index = sstore.getInput()[0];
if (!index.hasConstantValue())
continue;
Variable storageVar = ((Dataflow)dataflow).mustExplicitDataflow.getStorageVarForIndex(Dataflow.getInt(index.getConstantValue()));
if (dataflow.varMustDepOn(call, receiver, storageVar) == Status.SATISFIABLE)
return true;
}
// TODO: Check if the SLOAD instruction loads a constant offset and that there is an SSTORE with this offset
//return true;
}
return false;
}
@Override
protected boolean isCompliant(Instruction call, List<Instruction> methodInstructions, List<Instruction> contractInstructions, AbstractDataflow dataflow) {
assert (call instanceof Call);
Variable receiver = call.getInput()[1];
if (receiver.hasConstantValue())
return true;
if (dataflow.varMustDepOn(call, receiver, Caller.class) == Status.SATISFIABLE)
return true;
if (dataflow.varMustDepOn(call, receiver, CallDataLoad.class) == Status.SATISFIABLE)
return true;
if (dataflow.varMustDepOn(call, receiver, Address.class) == Status.SATISFIABLE)
return true;
if (dataflow.varMayDepOn(call, receiver, SLoad.class) == Status.SATISFIABLE) {
if (dataflow.varMayDepOn(call, receiver, AbstractDataflow.UNK_CONST_VAL) == Status.SATISFIABLE) {
return false;
}
for (Instruction sstore : contractInstructions) {
if (!(sstore instanceof SStore))
continue;
Variable index = sstore.getInput()[0];
if (!index.hasConstantValue())
continue;
Variable storageVar = ((Dataflow)dataflow).mayImplicitDataflow.getStorageVarForIndex(Dataflow.getInt(index.getConstantValue()));
if (dataflow.varMayDepOn(call, receiver, storageVar) == Status.SATISFIABLE) {
return false;
}
}
return true;
}
return false;
}
}
```
|
```package ch.securify.patterns;
import org.junit.Test;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
public class MissingInputValidationTest {
@Test
public void isViolation() throws IOException {
String hexViolation = "src/test/resources/solidity/MissingInputValidation.bin.hex";
HelperInstructionPattern helperInstructionPattern = new HelperInstructionPattern(hexViolation, new MissingInputValidation());
assertEquals(1, helperInstructionPattern.pattern.violations.size());
}
}```
|
Please help me generate a test for this class.
|
```package ch.securify.patterns;
import ch.securify.analysis.AbstractDataflow;
import ch.securify.analysis.Status;
import ch.securify.decompiler.Variable;
import ch.securify.decompiler.instructions.*;
import java.util.*;
public class MissingInputValidation extends AbstractInstructionPattern {
public MissingInputValidation() {
super(new PatternDescription("InsecureCodingPatterns",
MissingInputValidation.class,
"Missing Input Validation",
"Method arguments must be sanitized before they are used in computations.",
PatternDescription.Severity.Medium,
PatternDescription.Type.Trust));
}
@Override
protected boolean applicable(Instruction instr, AbstractDataflow dataflow) {
return instr instanceof _VirtualMethodHead;
}
@Override
protected boolean isViolation(Instruction instr, List<Instruction> methodInstructions, List<Instruction> contractInstructions, AbstractDataflow dataflow) {
Variable[] args = instr.getOutput();
for (Variable arg : args) {
if (!arg.getValueTypes().contains(CallDataLoad.class)) {
continue;
}
for (Instruction useInstr : methodInstructions) {
if (!(useInstr instanceof SStore
|| useInstr instanceof SLoad
|| useInstr instanceof MStore
|| useInstr instanceof MLoad
|| useInstr instanceof Sha3
|| useInstr instanceof Call))
continue;
for (Variable var : useInstr.getInput()) {
if (dataflow.varMustDepOn(useInstr, var, arg) == Status.SATISFIABLE) {
boolean varMayBeChecked = false;
for (Instruction checkInstr : methodInstructions) {
if (checkInstr instanceof JumpI) {
if (dataflow.mayFollow(checkInstr, useInstr) == Status.SATISFIABLE) {
Variable cond = ((JumpI) checkInstr).getCondition();
if (dataflow.varMayDepOn(checkInstr, cond, arg) == Status.SATISFIABLE) {
varMayBeChecked = true;
break;
}
}
}
}
if (!varMayBeChecked) {
return true;
}
}
}
}
}
return false;
}
@Override
protected boolean isCompliant(Instruction instr, List<Instruction> methodInstructions, List<Instruction> contractInstructions, AbstractDataflow dataflow) {
Variable[] args = instr.getOutput();
for (Variable arg : args) {
if (!arg.getValueTypes().contains(CallDataLoad.class)) {
continue;
}
for (Instruction useInstr : methodInstructions) {
if (!(useInstr instanceof SStore
|| useInstr instanceof SLoad
|| useInstr instanceof MStore
|| useInstr instanceof MLoad
|| useInstr instanceof Sha3
|| useInstr instanceof Call))
continue;
for (Variable var : useInstr.getInput()) {
if (dataflow.varMayDepOn(useInstr, var, arg) == Status.SATISFIABLE) {
boolean varChecked = false;
for (Instruction checkInstr : methodInstructions) {
if (checkInstr instanceof JumpI) {
if (dataflow.mustPrecede(checkInstr, useInstr) == Status.SATISFIABLE) {
Variable cond = ((JumpI) checkInstr).getCondition();
if (dataflow.varMustDepOn(checkInstr, cond, arg) == Status.SATISFIABLE) {
varChecked = true;
break;
}
}
}
}
if (!varChecked)
return false;
}
}
}
}
return true;
}
}
```
|
```package ch.securify.patterns;
import org.junit.Test;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
public class DAOConstantGasTest {
@Test
public void isViolation() throws IOException {
String hexViolation = "src/test/resources/solidity/DAOConstantGas.bin.hex";
HelperInstructionPattern helperInstructionPattern = new HelperInstructionPattern(hexViolation, new DAOConstantGas());
assertEquals(1, helperInstructionPattern.pattern.violations.size());
}
}```
|
Please help me generate a test for this class.
|
```package ch.securify.patterns;
import java.util.List;
import ch.securify.analysis.Status;
import ch.securify.analysis.AbstractDataflow;
import ch.securify.decompiler.Variable;
import ch.securify.decompiler.instructions.Call;
import ch.securify.decompiler.instructions.Gas;
import ch.securify.decompiler.instructions.Instruction;
import ch.securify.decompiler.instructions.SStore;
public class DAOConstantGas extends AbstractInstructionPattern {
public DAOConstantGas() {
super(new PatternDescription("RecursiveCalls",
DAOConstantGas.class,
"Reentrancy with constant gas",
"Ether transfers (such as send and transfer) that are followed by state changes may be reentrant.",
PatternDescription.Severity.Critical,
PatternDescription.Type.Security));
}
@Override
protected boolean applicable(Instruction instr, AbstractDataflow dataflow) {
if (!(instr instanceof Call) || ((Call) instr).isBuiltInContractCall())
return false;
Variable value = instr.getInput()[2];
if (value.hasConstantValue() && AbstractDataflow.getInt(value.getConstantValue()) == 0)
return false;
Variable gasVar = instr.getInput()[0];
if (dataflow.varMayDepOn(instr, gasVar, Gas.class) == Status.SATISFIABLE)
return false;
return true;
}
@Override
protected boolean isViolation(Instruction instr, List<Instruction> methodInstructions, List<Instruction> contractInstructions, AbstractDataflow dataflow) {
for (Instruction otherInstr : methodInstructions) {
if (otherInstr instanceof SStore) {
if (dataflow.mustPrecede(instr, otherInstr) == Status.SATISFIABLE) {
return true;
}
}
}
return false;
}
@Override
protected boolean isCompliant(Instruction instr, List<Instruction> methodInstructions, List<Instruction> contractInstructions, AbstractDataflow dataflow) {
for (Instruction otherInstr : methodInstructions) {
if (otherInstr instanceof SStore) {
if (dataflow.mayFollow(instr, otherInstr) == Status.SATISFIABLE) {
return false;
}
}
}
return true;
}
}
```
|
```package ch.securify.patterns;
import org.junit.Test;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
public class LockedEtherTest {
@Test
public void isViolation() throws IOException {
String hex = "src/test/resources/solidity/LockedEther.bin.hex";
ContractPatternTest instructionPatternTest = new ContractPatternTest(hex, new LockedEther());
// as many violations as there are functions in the smart contract
assertEquals(2, instructionPatternTest.pattern.violations.size());
}
@Test
public void isNoViolationDelegate() throws IOException {
String hex = "src/test/resources/solidity/LockedEtherDelegate.bin.hex";
ContractPatternTest instructionPatternTest = new ContractPatternTest(hex, new LockedEther());
// as many violations as there are functions in the smart contract
assertEquals(0, instructionPatternTest.pattern.violations.size());
assertEquals(0, instructionPatternTest.pattern.warnings.size());
assertEquals(1, instructionPatternTest.pattern.safe.size());
}
}```
|
Please help me generate a test for this class.
|
```package ch.securify.patterns;
import java.math.BigInteger;
import java.util.List;
import ch.securify.analysis.Status;
import ch.securify.analysis.AbstractDataflow;
import ch.securify.decompiler.Variable;
import ch.securify.decompiler.instructions.*;
import ch.securify.utils.BigIntUtil;
public class LockedEther extends AbstractContractPattern {
public LockedEther() {
super(new PatternDescription("LockedEther",
LockedEther.class,
"Locked Ether",
"Contracts that may receive ether must also allow users to extract the deposited ether from the contract.",
PatternDescription.Severity.Medium,
PatternDescription.Type.Security));
}
private boolean allStopsCannotReceiveEther(List<Instruction> instructions, AbstractDataflow dataflow) {
for (Instruction haltInstr : instructions) {
if (haltInstr instanceof Stop || haltInstr instanceof Return) {
boolean stopCannotReceiveEther = false;
for (Instruction jumpInstr : instructions) {
if (jumpInstr instanceof JumpI) {
Variable cond = ((JumpI) jumpInstr).getCondition();
if (dataflow.mustPrecede(jumpInstr, haltInstr) == Status.SATISFIABLE
&& dataflow.varMustDepOn(jumpInstr, cond, CallValue.class) == Status.SATISFIABLE
&& dataflow.varMustDepOn(jumpInstr, cond, IsZero.class) == Status.SATISFIABLE) {
stopCannotReceiveEther = true;
break;
}
}
}
if (!stopCannotReceiveEther) {
return false;
}
}
}
return true;
}
@Override
protected boolean isSafe(List<Instruction> instructions, AbstractDataflow dataflow) {
if (allStopsCannotReceiveEther(instructions, dataflow)) {
return true;
}
// Check if the contract can send ether (has a call instruction with positive amount or a selfdestruct)
for (Instruction instr : instructions) {
if (instr instanceof SelfDestruct) {
return true;
}
if (!(instr instanceof CallingInstruction))
continue;
if (instr instanceof DelegateCall) {
return true;
}
CallingInstruction callInstr = (CallingInstruction) instr;
Variable amount = callInstr.getValue();
if (amount.hasConstantValue() && AbstractDataflow.getInt(amount.getConstantValue()) != 0
|| dataflow.varMustDepOn(callInstr, amount, Balance.class) == Status.SATISFIABLE
|| dataflow.varMustDepOn(callInstr, amount, CallDataLoad.class) == Status.SATISFIABLE
|| dataflow.varMustDepOn(callInstr, amount, CallValue.class) == Status.SATISFIABLE
|| dataflow.varMustDepOn(callInstr, amount, MLoad.class) == Status.SATISFIABLE
|| dataflow.varMustDepOn(callInstr, amount, SLoad.class) == Status.SATISFIABLE) {
return true;
}
}
return false;
}
@Override
protected boolean isViolation(List<Instruction> instructions, AbstractDataflow dataflow) {
if (allStopsCannotReceiveEther(instructions, dataflow)) {
return false;
}
// check if the contract can transfer ether
for (Instruction callInstr : instructions) {
if (callInstr instanceof CallingInstruction) {
if (callInstr instanceof DelegateCall) {
return false;
} else {
Variable amount = ((CallingInstruction) callInstr).getValue();
if (!amount.hasConstantValue() || BigIntUtil.fromInt256(amount.getConstantValue()).compareTo(BigInteger.ZERO) != 0) {
return false;
}
}
} else if (callInstr instanceof SelfDestruct) {
return false;
}
}
return true;
}
}
```
|
```package ch.securify.patterns;
import ch.securify.decompiler.instructions.Instruction;
import java.io.IOException;
import java.util.List;
class ContractPatternTest {
AbstractPattern pattern;
public ContractPatternTest(String hexFilename, AbstractContractPattern pattern) throws IOException {
HelperTestInput testInput = new HelperTestInput(hexFilename);
this.pattern = pattern;
for (List<Instruction> methodBody : testInput.methodBodies) {
pattern.checkPattern(methodBody, testInput.instructions, testInput.dataflow);
}
}
}
```
|
Please help me generate a test for this class.
|
```package ch.securify.model;
public class Contract {
private String contractAddress;
//private String init;
private String code;
public String getContractAddress() {
return contractAddress;
}
public String getCode() {
return code.substring(2);
}
public void setCode(String code) {
this.code = code;
}
}
```
|
```package ch.securify.patterns;
import org.junit.Test;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
public class UnrestrictedEtherFlowTest {
@Test
public void isWarning() throws IOException {
// only warning because of the hashing operation
String hex = "src/test/resources/solidity/UnrestrictedEtherFlow.bin.hex";
HelperInstructionPattern helperInstructionPattern = new HelperInstructionPattern(hex, new UnrestrictedEtherFlow());
assertEquals(1, helperInstructionPattern.pattern.warnings.size());
}
@Test
public void isViolation() throws IOException {
String hex = "src/test/resources/solidity/UnrestrictedEtherFlow2.bin.hex";
HelperInstructionPattern helperInstructionPattern = new HelperInstructionPattern(hex, new UnrestrictedEtherFlow());
assertEquals(1, helperInstructionPattern.pattern.violations.size());
}
}```
|
Please help me generate a test for this class.
|
```package ch.securify.patterns;
import java.util.List;
import ch.securify.analysis.AbstractDataflow;
import ch.securify.analysis.Status;
import ch.securify.decompiler.Variable;
import ch.securify.decompiler.instructions.*;
public class UnrestrictedEtherFlow extends AbstractInstructionPattern {
public UnrestrictedEtherFlow() {
super(new PatternDescription("InsecureCodingPatterns",
UnrestrictedEtherFlow.class,
"Unrestricted ether flow",
"The execution of ether flows should be restricted to an authorized set of users.",
PatternDescription.Severity.Critical,
PatternDescription.Type.Security));
}
@Override
protected boolean applicable(Instruction instr, AbstractDataflow dataflow) {
return instr instanceof Call;
}
@Override
protected boolean isViolation(Instruction call, List<Instruction> methodInstructions, List<Instruction> contractInstructions, AbstractDataflow dataflow) {
assert (call instanceof Call);
if (dataflow.instrMayDepOn(call, Caller.class) == Status.SATISFIABLE) {
// the transfer may depend on who is the caller
return false;
}
Variable amount = call.getInput()[2];
if (amount.hasConstantValue() && AbstractDataflow.getInt(amount.getConstantValue()) == 0) {
// the amount is zero
return false;
}
if (amount.hasConstantValue() && AbstractDataflow.getInt(amount.getConstantValue()) > 0) {
// the amount is a positive constant
return true;
}
if (dataflow.varMustDepOn(call, amount, CallDataLoad.class) == Status.SATISFIABLE) {
// the amount can be influenced by the caller
return true;
}
return false;
}
@Override
protected boolean isCompliant(Instruction call, List<Instruction> methodInstructions, List<Instruction> contractInstructions, AbstractDataflow dataflow) {
assert(call instanceof Call);
Variable value = call.getInput()[2];
if (value.hasConstantValue() && AbstractDataflow.getInt(value.getConstantValue()) == 0) {
// the amount is zero
return true;
}
for (Instruction jump : methodInstructions) {
if (!(jump instanceof JumpI))
continue;
if (dataflow.mustPrecede(jump, call) == Status.SATISFIABLE) {
Variable cond = ((JumpI) jump).getCondition();
if (dataflow.varMustDepOn(jump, cond, Caller.class) == Status.SATISFIABLE) {
// there must be a jump instruction that preceeds the call and whose condition depends on the caller
return true;
}
}
}
return false;
}
}
```
|
```package ch.securify.patterns;
import org.junit.Test;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
public class UnrestrictedWriteTest {
@Test
public void isViolation() throws IOException {
String hex = "src/test/resources/solidity/UnrestrictedWrite.bin.hex";
HelperInstructionPattern helperInstructionPattern = new HelperInstructionPattern(hex, new UnrestrictedWrite());
assertEquals(1, helperInstructionPattern.pattern.violations.size());
}
}```
|
Please help me generate a test for this class.
|
```package ch.securify.patterns;
import java.util.List;
import ch.securify.analysis.Status;
import ch.securify.analysis.AbstractDataflow;
import ch.securify.decompiler.Variable;
import ch.securify.decompiler.instructions.Caller;
import ch.securify.decompiler.instructions.Instruction;
import ch.securify.decompiler.instructions.JumpI;
import ch.securify.decompiler.instructions.SStore;
public class UnrestrictedWrite extends AbstractInstructionPattern {
public UnrestrictedWrite() {
super(new PatternDescription("InsecureCodingPatterns",
UnrestrictedWrite.class,
"Unrestricted write to storage",
"Contract fields that can be modified by any user must be inspected.",
PatternDescription.Severity.Critical,
PatternDescription.Type.Security));
}
@Override
protected boolean applicable(Instruction instr, AbstractDataflow dataflow) {
return instr instanceof SStore;
}
@Override
protected boolean isViolation(Instruction instr, List<Instruction> methodInstructions, List<Instruction> contractInstructions, AbstractDataflow dataflow) {
assert(instr instanceof SStore);
if (dataflow.varMayDepOn(instr, instr.getInput()[0], Caller.class) == Status.SATISFIABLE)
return false;
if (dataflow.instrMayDepOn(instr, Caller.class) == Status.SATISFIABLE)
return false;
return true;
}
@Override
protected boolean isCompliant(Instruction sstore, List<Instruction> methodInstructions, List<Instruction> contractInstructions, AbstractDataflow dataflow) {
assert(sstore instanceof SStore);
if (dataflow.varMustDepOn(sstore, sstore.getInput()[0], Caller.class) == Status.SATISFIABLE) {
return true;
}
for (Instruction jump : methodInstructions) {
if (!(jump instanceof JumpI))
continue;
if (dataflow.mustPrecede(jump, sstore) == Status.SATISFIABLE) {
Variable cond = ((JumpI) jump).getCondition();
if (dataflow.varMustDepOn(jump, cond, Caller.class) == Status.SATISFIABLE) {
return true;
}
}
}
return false;
}
}
```
|
```package ch.securify;
import org.junit.Test;
import java.util.List;
import static org.junit.Assert.*;
public class CompilationHelpersTest {
@Test
public void bytecodeOffsetToSourceOffset() {
testBytecodeOffsetToSourceOffset("0:1:1;1:1:1;2:1:1;;;3:1:1", 1,0);
testBytecodeOffsetToSourceOffset("0:1:1;1:1:1;2:1:1;;;3:1:1", 2,1);
testBytecodeOffsetToSourceOffset("0:1:1;1:1:1;2:1:1;;;3:1:1", 6,3);
testBytecodeOffsetToSourceOffset("0:1:1;1:1:1;2:1:1;;;3:1:1", 5,2);
}
public void testBytecodeOffsetToSourceOffset(String map, int index, int res) {
List<String[]> explodedMap = CompilationHelpers.explodeMappingString(map);
assertEquals(CompilationHelpers.bytecodeOffsetToSourceOffset(index, explodedMap), res );
}
}```
|
Please help me generate a test for this class.
|
```package ch.securify;
import ch.securify.analysis.SecurifyErrors;
import ch.securify.utils.Hex;
import com.google.common.base.CharMatcher;
import com.google.gson.*;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Collections.reverse;
class SmallPatternResult {
String name;
TreeSet<Integer> violations;
TreeSet<Integer> warnings;
TreeSet<Integer> safe;
TreeSet<Integer> conflicts;
SmallPatternResult(TreeSet<Integer> violations, TreeSet<Integer> warnings, TreeSet<Integer> safe, TreeSet<Integer> conflicts) {
this.violations = violations;
this.warnings = warnings;
this.safe = safe;
this.conflicts = conflicts;
}
}
class MappingNotFoundException extends RuntimeException {
RuntimeException baseException;
int bytecodeOffset;
public MappingNotFoundException(){
}
public MappingNotFoundException(RuntimeException e, int bytecodeOffset) {
this.baseException = e;
this.bytecodeOffset = bytecodeOffset;
}
}
public class CompilationHelpers {
public static String sanitizeLibraries(String hexCode) {
final String dummyAddress = "1000000000000000000000000000000000000010";
StringBuilder sanitized = new StringBuilder();
for (int i = 0; i < hexCode.length(); i++) {
if (hexCode.charAt(i) == '_') {
sanitized.append(dummyAddress);
i += dummyAddress.length() - 1;
} else {
sanitized.append(hexCode.charAt(i));
}
}
return sanitized.toString();
}
public static byte[] extractBinaryFromHexFile(String filehex) throws IOException {
File contractBinHexFile = new File(filehex);
String hexCode = Files.readAllLines(contractBinHexFile.toPath()).get(0);
return Hex.decode(sanitizeLibraries(hexCode));
}
static int bytecodeOffsetToSourceOffset(int bytecodeOffset, List<String[]> map) throws MappingNotFoundException {
try {
map = map.subList(0, bytecodeOffset);
} catch (IndexOutOfBoundsException | IllegalArgumentException e) {
throw new MappingNotFoundException(e, bytecodeOffset);
}
reverse(map);
for (String[] offset : map) {
if (!offset[0].equals("")) {
int res = Integer.parseInt(offset[0]);
if (res < 0) {
throw new MappingNotFoundException();
}
return res;
}
}
throw new MappingNotFoundException();
}
static List<String[]> explodeMappingString(String map) {
ArrayList<String[]> mapping = new ArrayList<>();
for (String s : map.split(";")) {
mapping.add(s.split(":"));
}
return mapping;
}
private static String readFile(String path) throws IOException {
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, Charset.defaultCharset());
}
static JsonObject compileContracts(String solc, String filesol) throws IOException, InterruptedException, RuntimeException {
ProcessBuilder p = new ProcessBuilder(solc, "--combined-json", "abi,ast,bin-runtime,srcmap-runtime", filesol);
File f = File.createTempFile("securify_compilation_", ".json");
f.deleteOnExit();
File fErr = File.createTempFile("securify_compilation_error", ".log");
fErr.deleteOnExit();
final Process process = p.redirectOutput(f).redirectError(fErr).start();
process.waitFor();
int exitValue = process.exitValue();
if(exitValue != 0){
System.err.print(readFile(fErr.getPath()));
throw new RuntimeException();
}
JsonObject jsonObject = new JsonParser().parse(readFile(f.getPath())).getAsJsonObject();
return jsonObject.get("contracts").getAsJsonObject();
}
static JsonObject parseCompilationOutput(String compilationOutputFile) throws IOException {
return new JsonParser().parse(readFile(compilationOutputFile)).getAsJsonObject();
}
private static TreeSet<Integer> getMatchedLines(byte[] contract, JsonArray matches, String map, SecurifyErrors securifyErrors) throws MappingNotFoundException {
TreeSet<Integer> matchedLines = new TreeSet<>();
for (JsonElement m : matches) {
int byteOffset = m.getAsInt();
int line;
try {
int srcOffset = CompilationHelpers.bytecodeOffsetToSourceOffset(byteOffset, CompilationHelpers.explodeMappingString(map));
String matchingSubstring = new String(Arrays.copyOfRange(contract, 0, srcOffset), UTF_8);
line = CharMatcher.is('\n').countIn(matchingSubstring);
} catch (MappingNotFoundException e) {
line = -1;
securifyErrors.add("mapping_error", e);
}
matchedLines.add(line);
}
return matchedLines;
}
static SolidityResult getMappingsFromStatusFile(String livestatusfile, String map, byte[] contract) throws IOException {
JsonObject jsonObject = new JsonParser().parse(readFile(livestatusfile)).getAsJsonObject();
Set<Map.Entry<String, JsonElement>> results = jsonObject.get("patternResults").getAsJsonObject().entrySet();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
SecurifyErrors securifyErrors = gson.fromJson(jsonObject.get("securifyErrors"), SecurifyErrors.class);
SolidityResult allResults = new SolidityResult(securifyErrors);
for (Map.Entry<String, JsonElement> e : results) {
JsonArray violations = e.getValue().getAsJsonObject().get("violations").getAsJsonArray();
JsonArray safe = e.getValue().getAsJsonObject().get("safe").getAsJsonArray();
JsonArray warnings = e.getValue().getAsJsonObject().get("warnings").getAsJsonArray();
JsonArray conflicts = e.getValue().getAsJsonObject().get("conflicts").getAsJsonArray();
SmallPatternResult pResults = new SmallPatternResult(
getMatchedLines(contract, violations, map, allResults.securifyErrors),
getMatchedLines(contract, warnings, map, allResults.securifyErrors),
getMatchedLines(contract, safe, map, allResults.securifyErrors),
getMatchedLines(contract, conflicts, map, allResults.securifyErrors));
allResults.results.put(e.getKey(), pResults);
}
return allResults;
}
}
```
|
```package ch.securify.patterns;
import org.junit.Test;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
public class DAOTest {
@Test
public void isViolation() throws IOException {
String hexViolating = "src/test/resources/solidity/reentrancy.bin.hex";
HelperInstructionPattern helperInstructionPattern = new HelperInstructionPattern(hexViolating, new DAO());
assertEquals(1, helperInstructionPattern.pattern.violations.size());
}
@Test
public void isCompliant() throws IOException {
String hexSafe = "src/test/resources/solidity/no-reentrancy.bin.hex";
HelperInstructionPattern helperInstructionPattern = new HelperInstructionPattern(hexSafe, new DAO());
assertEquals(1, helperInstructionPattern.pattern.safe.size());
}
}```
|
Please help me generate a test for this class.
|
```package ch.securify.patterns;
import ch.securify.analysis.AbstractDataflow;
import ch.securify.analysis.Status;
import ch.securify.decompiler.Variable;
import ch.securify.decompiler.instructions.Call;
import ch.securify.decompiler.instructions.Gas;
import ch.securify.decompiler.instructions.Instruction;
import ch.securify.decompiler.instructions.SStore;
import java.util.List;
public class DAO extends AbstractInstructionPattern {
public DAO() {
super(new PatternDescription("RecursiveCalls",
DAO.class,
"Gas-dependent Reentrancy",
"Calls into external contracts that receive all remaining gas and are followed by state changes may be reentrant.",
PatternDescription.Severity.Critical,
PatternDescription.Type.Security));
}
@Override
protected boolean applicable(Instruction instr, AbstractDataflow dataflow) {
if (!(instr instanceof Call) || ((Call) instr).isBuiltInContractCall())
return false;
Variable value = instr.getInput()[2];
if (value.hasConstantValue() && AbstractDataflow.getInt(value.getConstantValue()) == 0)
return false;
Variable gasVar = instr.getInput()[0];
if (dataflow.varMayDepOn(instr, gasVar, Gas.class) == Status.UNSATISFIABLE)
return false;
return true;
}
@Override
protected boolean isViolation(Instruction instr, List<Instruction> methodInstructions, List<Instruction> contractInstructions, AbstractDataflow dataflow) {
for (Instruction otherInstr : methodInstructions) {
if (otherInstr instanceof SStore) {
int s = dataflow.mustPrecede(instr, otherInstr);
if (s == Status.SATISFIABLE) {
return true;
}
}
}
return false;
}
@Override
protected boolean isCompliant(Instruction instr, List<Instruction> methodInstructions, List<Instruction> contractInstructions, AbstractDataflow dataflow) {
for (Instruction otherInstr : methodInstructions) {
if (otherInstr instanceof SStore) {
int s = dataflow.mayFollow(instr, otherInstr);
if (s == Status.SATISFIABLE) {
return false;
}
}
}
return true;
}
}
```
|
```package ch.securify.patterns;
import org.junit.Test;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
public class TODAmountTest {
@Test
public void isViolation() throws IOException {
String hex = "src/test/resources/solidity/TODAmount.bin.hex";
HelperInstructionPattern helperInstructionPattern = new HelperInstructionPattern(hex, new TODAmount());
assertEquals(1, helperInstructionPattern.pattern.violations.size());
}
}```
|
Please help me generate a test for this class.
|
```package ch.securify.patterns;
import java.util.List;
import ch.securify.analysis.AbstractDataflow;
import ch.securify.analysis.Dataflow;
import ch.securify.analysis.Status;
import ch.securify.decompiler.Variable;
import ch.securify.decompiler.instructions.*;
public class TODAmount extends AbstractInstructionPattern {
public TODAmount(){
super(new PatternDescription("TransactionReordering",
TODAmount.class,
"Transaction Order Affects Ether Amount",
"The amount of ether transferred must not be influenced by other transactions.",
PatternDescription.Severity.Critical,
PatternDescription.Type.Security));
}
@Override
protected boolean applicable(Instruction instr, AbstractDataflow dataflow) {
if (!(instr instanceof Call) || ((Call) instr).isBuiltInContractCall())
return false;
Variable value = instr.getInput()[2];
if (value.hasConstantValue() && AbstractDataflow.getInt(value.getConstantValue()) == 0)
return false;
return true;
}
@Override
protected boolean isViolation(Instruction instr, List<Instruction> methodInstructions, List<Instruction> contractInstructions, AbstractDataflow dataflow) {
if (instr instanceof Call) {
Variable amount = instr.getInput()[2];
if (dataflow.varMustDepOn(instr, amount, SLoad.class) == Status.SATISFIABLE) {
for (Instruction sstore : contractInstructions) {
if (!(sstore instanceof SStore))
continue;
Variable index = sstore.getInput()[0];
if (!index.hasConstantValue())
continue;
Variable storageVar = ((Dataflow)dataflow).mustExplicitDataflow.getStorageVarForIndex(Dataflow.getInt(index.getConstantValue()));
if (dataflow.varMustDepOn(instr, amount, storageVar) == Status.SATISFIABLE)
return true;
}
// TODO: Check if the SLOAD instruction loads a constant offset and that there is an SSTORE with this offset
//return true;
}
if (dataflow.varMustDepOn(instr, amount, Balance.class) == Status.SATISFIABLE) {
// TODO: Assumes balance is not constant across transactions
return true;
}
}
return false;
}
@Override
protected boolean isCompliant(Instruction instr, List<Instruction> methodInstructions, List<Instruction> contractInstructions, AbstractDataflow dataflow) {
assert(instr instanceof Call);
Variable amount = instr.getInput()[2];
if (amount.hasConstantValue())
return true;
if (dataflow.varMustDepOn(instr, amount, Caller.class) == Status.SATISFIABLE)
return true;
if (dataflow.varMustDepOn(instr, amount, CallDataLoad.class) == Status.SATISFIABLE)
return true;
if (dataflow.varMayDepOn(instr, amount, Balance.class) == Status.SATISFIABLE) {
return false;
}
if (dataflow.varMayDepOn(instr, amount, SLoad.class) == Status.SATISFIABLE) {
if (dataflow.varMayDepOn(instr, amount, AbstractDataflow.UNK_CONST_VAL) == Status.SATISFIABLE) {
return false;
}
for (Instruction sstore : contractInstructions) {
if (!(sstore instanceof SStore))
continue;
Variable index = sstore.getInput()[0];
if (!index.hasConstantValue())
continue;
Variable storageVar = ((Dataflow)dataflow).mayImplicitDataflow.getStorageVarForIndex(Dataflow.getInt(index.getConstantValue()));
if (dataflow.varMayDepOn(instr, amount, storageVar) == Status.SATISFIABLE) {
return false;
}
}
return true;
}
return false;
}
}
```
|
```package ch.securify.patterns;
import ch.securify.decompiler.instructions.Instruction;
import java.io.IOException;
import java.util.List;
public class HelperInstructionPattern {
AbstractPattern pattern;
public HelperInstructionPattern(String hexFilename, AbstractInstructionPattern pattern) throws IOException {
HelperTestInput helperTestInput = new HelperTestInput(hexFilename);
this.pattern = pattern;
for (List<Instruction> methodBody : helperTestInput.methodBodies) {
pattern.checkPattern(methodBody, helperTestInput.instructions, helperTestInput.dataflow);
}
}
}
```
|
Please help me generate a test for this class.
|
```package ch.securify.decompiler.instructions;
/**
* Marker interface for instructions that define the type of their output variables.
*/
public interface _TypeInstruction {
}
```
|
```package ch.securify.patterns;
import org.junit.Test;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
public class TODTransferTest {
// TODO: fix
// @Test
// public void isWarning() throws IOException {
// String hex = "src/test/resources/solidity/TODTransfer.bin.hex";
// HelperInstructionPattern helperInstructionPattern = new HelperInstructionPattern(hex, new TODTransfer());
// assertEquals(1, helperInstructionPattern.pattern.warnings.size());
// }
// TODO: fix
// @Test
// public void isViolation() throws IOException {
// String hex = "src/test/resources/solidity/TODTransfer2.bin.hex";
// HelperInstructionPattern helperInstructionPattern = new HelperInstructionPattern(hex, new TODTransfer());
// assertEquals(1, helperInstructionPattern.pattern.violations.size());
// }
}
```
|
Please help me generate a test for this class.
|
```package ch.securify.patterns;
import java.util.List;
import ch.securify.analysis.AbstractDataflow;
import ch.securify.analysis.Dataflow;
import ch.securify.analysis.Status;
import ch.securify.decompiler.Variable;
import ch.securify.decompiler.instructions.*;
public class TODTransfer extends AbstractInstructionPattern {
public TODTransfer() {
super(new PatternDescription("TransactionReordering",
TODTransfer.class,
"Transaction Order Affects Execution of Ether Transfer",
"Ether transfers whose execution can be manipulated by other transactions must be inspected for unintended behavior.",
PatternDescription.Severity.Critical,
PatternDescription.Type.Security));
}
@Override
protected boolean applicable(Instruction instr, AbstractDataflow dataflow) {
if (!(instr instanceof Call) || ((Call) instr).isBuiltInContractCall())
return false;
Variable value = instr.getInput()[2];
if (value.hasConstantValue() && AbstractDataflow.getInt(value.getConstantValue()) == 0)
return false;
return true;
}
@Override
protected boolean isViolation(Instruction call, List<Instruction> methodInstructions, List<Instruction> contractInstructions, AbstractDataflow dataflow) {
assert(call instanceof Call);
for (Instruction jump : methodInstructions) {
if (!(jump instanceof JumpI))
continue;
if (dataflow.mustPrecede(jump, call) == Status.UNSATISFIABLE)
continue;
Variable cond = ((JumpI)jump).getCondition();
if (dataflow.varMustDepOn(jump, cond, SLoad.class) == Status.SATISFIABLE) {
for (Instruction sstore : contractInstructions) {
if (!(sstore instanceof SStore))
continue;
Variable index = sstore.getInput()[0];
if (!index.hasConstantValue())
continue;
Variable storageVar = ((Dataflow)dataflow).mustExplicitDataflow.getStorageVarForIndex(Dataflow.getInt(index.getConstantValue()));
if (dataflow.varMustDepOn(jump, cond, storageVar) == Status.SATISFIABLE)
return true;
}
//return true;
}
}
return false;
}
@Override
protected boolean isCompliant(Instruction call, List<Instruction> methodInstructions, List<Instruction> contractInstructions, AbstractDataflow dataflow) {
assert(call instanceof Call);
if (dataflow.instrMayDepOn(call, SLoad.class) == Status.UNSATISFIABLE) {
if (dataflow.instrMayDepOn(call, Balance.class) == Status.UNSATISFIABLE) {
return true;
}
} else {
for (Instruction jump : methodInstructions) {
if (!(jump instanceof JumpI))
continue;
if (dataflow.mayFollow(jump, call) == Status.UNSATISFIABLE)
continue;
Variable cond = ((JumpI) jump).getCondition();
if (dataflow.varMayDepOn(jump, cond, AbstractDataflow.UNK_CONST_VAL) == Status.SATISFIABLE) {
return false;
}
for (Instruction sstore : contractInstructions) {
if (!(sstore instanceof SStore))
continue;
Variable index = sstore.getInput()[0];
if (!index.hasConstantValue())
continue;
Variable storageVar = ((Dataflow)dataflow).mayImplicitDataflow.getStorageVarForIndex(Dataflow.getInt(index.getConstantValue()));
if (dataflow.varMayDepOn(jump, cond, storageVar) == Status.SATISFIABLE) {
return false;
}
}
return true;
}
}
return false;
}
}
```
|
```package com.lambdaworks.crypto.test;
import com.lambdaworks.crypto.PBKDF;
import org.junit.Test;
import java.math.BigInteger;
import static org.junit.Assert.*;
import static com.lambdaworks.crypto.test.CryptoTestUtil.*;
public class PBKDFTest {
@Test
public void pbkdf2_hmac_sha1_rfc6070() throws Exception {
String alg = "HmacSHA1";
byte[] P, S;
int c, dkLen;
String DK;
P = "password".getBytes("UTF-8");
S = "salt".getBytes("UTF-8");
c = 1;
dkLen = 20;
DK = "0c60c80f961f0e71f3a9b524af6012062fe037a6";
assertArrayEquals(decode(DK), PBKDF.pbkdf2(alg, P, S, c, dkLen));
P = "password".getBytes("UTF-8");
S = "salt".getBytes("UTF-8");
c = 2;
dkLen = 20;
DK = "ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957";
assertArrayEquals(decode(DK), PBKDF.pbkdf2(alg, P, S, c, dkLen));
P = "password".getBytes("UTF-8");
S = "salt".getBytes("UTF-8");
c = 4096;
dkLen = 20;
DK = "4b007901b765489abead49d926f721d065a429c1";
assertArrayEquals(decode(DK), PBKDF.pbkdf2(alg, P, S, c, dkLen));
P = "password".getBytes("UTF-8");
S = "salt".getBytes("UTF-8");
c = 16777216;
dkLen = 20;
DK = "eefe3d61cd4da4e4e9945b3d6ba2158c2634e984";
assertArrayEquals(decode(DK), PBKDF.pbkdf2(alg, P, S, c, dkLen));
P = "passwordPASSWORDpassword".getBytes("UTF-8");
S = "saltSALTsaltSALTsaltSALTsaltSALTsalt".getBytes("UTF-8");
c = 4096;
dkLen = 25;
DK = "3d2eec4fe41c849b80c8d83662c0e44a8b291a964cf2f07038";
assertArrayEquals(decode(DK), PBKDF.pbkdf2(alg, P, S, c, dkLen));
P = "pass\0word".getBytes("UTF-8");
S = "sa\0lt".getBytes("UTF-8");
c = 4096;
dkLen = 16;
DK = "56fa6aa75548099dcc37d7f03425e0c3";
assertArrayEquals(decode(DK), PBKDF.pbkdf2(alg, P, S, c, dkLen));
}
@Test
public void pbkdf2_hmac_sha1_rfc3962() throws Exception {
String alg = "HmacSHA1";
byte[] P, S;
int c, dkLen;
String DK;
P = "password".getBytes("UTF-8");
S = "ATHENA.MIT.EDUraeburn".getBytes("UTF-8");
c = 1;
dkLen = 16;
DK = "cdedb5281bb2f801565a1122b2563515";
assertArrayEquals(decode(DK), PBKDF.pbkdf2(alg, P, S, c, dkLen));
dkLen = 32;
DK = "cdedb5281bb2f801565a1122b25635150ad1f7a04bb9f3a333ecc0e2e1f70837";
assertArrayEquals(decode(DK), PBKDF.pbkdf2(alg, P, S, c, dkLen));
P = "password".getBytes("UTF-8");
S = "ATHENA.MIT.EDUraeburn".getBytes("UTF-8");
c = 2;
dkLen = 16;
DK = "01dbee7f4a9e243e988b62c73cda935d";
assertArrayEquals(decode(DK), PBKDF.pbkdf2(alg, P, S, c, dkLen));
dkLen = 32;
DK = "01dbee7f4a9e243e988b62c73cda935da05378b93244ec8f48a99e61ad799d86";
assertArrayEquals(decode(DK), PBKDF.pbkdf2(alg, P, S, c, dkLen));
P = "password".getBytes("UTF-8");
S = "ATHENA.MIT.EDUraeburn".getBytes("UTF-8");
c = 1200;
dkLen = 16;
DK = "5c08eb61fdf71e4e4ec3cf6ba1f5512b";
assertArrayEquals(decode(DK), PBKDF.pbkdf2(alg, P, S, c, dkLen));
dkLen = 32;
DK = "5c08eb61fdf71e4e4ec3cf6ba1f5512ba7e52ddbc5e5142f708a31e2e62b1e13";
assertArrayEquals(decode(DK), PBKDF.pbkdf2(alg, P, S, c, dkLen));
P = "password".getBytes("UTF-8");
S = new BigInteger("1234567878563412", 16).toByteArray();
c = 5;
dkLen = 16;
DK = "d1daa78615f287e6a1c8b120d7062a49";
assertArrayEquals(decode(DK), PBKDF.pbkdf2(alg, P, S, c, dkLen));
dkLen = 32;
DK = "d1daa78615f287e6a1c8b120d7062a493f98d203e6be49a6adf4fa574b6e64ee";
assertArrayEquals(decode(DK), PBKDF.pbkdf2(alg, P, S, c, dkLen));
}
@Test
public void pbkdf2_hmac_sha256_scrypt() throws Exception {
String alg = "HmacSHA256";
byte[] P, S;
int c, dkLen;
String DK;
P = "password".getBytes("UTF-8");
S = "salt".getBytes("UTF-8");
c = 4096;
dkLen = 32;
DK = "c5e478d59288c841aa530db6845c4c8d962893a001ce4e11a4963873aa98134a";
assertArrayEquals(decode(DK), PBKDF.pbkdf2(alg, P, S, c, dkLen));
}
}
```
|
Please help me generate a test for this class.
|
```package com.lambdaworks.crypto;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.GeneralSecurityException;
import static java.lang.System.arraycopy;
/**
* An implementation of the Password-Based Key Derivation Function as specified
* in RFC 2898.
*
* @author Will Glozer
*/
public class PBKDF {
/**
* Implementation of PBKDF2 (RFC2898).
*
* @param alg HMAC algorithm to use.
* @param P Password.
* @param S Salt.
* @param c Iteration count.
* @param dkLen Intended length, in octets, of the derived key.
*
* @return The derived key.
*
* @throws GeneralSecurityException
*/
public static byte[] pbkdf2(String alg, byte[] P, byte[] S, int c, int dkLen) throws GeneralSecurityException {
Mac mac = Mac.getInstance(alg);
mac.init(new SecretKeySpec(P, alg));
byte[] DK = new byte[dkLen];
pbkdf2(mac, S, c, DK, dkLen);
return DK;
}
/**
* Implementation of PBKDF2 (RFC2898).
*
* @param mac Pre-initialized {@link Mac} instance to use.
* @param S Salt.
* @param c Iteration count.
* @param DK Byte array that derived key will be placed in.
* @param dkLen Intended length, in octets, of the derived key.
*
* @throws GeneralSecurityException
*/
public static void pbkdf2(Mac mac, byte[] S, int c, byte[] DK, int dkLen) throws GeneralSecurityException {
int hLen = mac.getMacLength();
if (dkLen > (Math.pow(2, 32) - 1) * hLen) {
throw new GeneralSecurityException("Requested key length too long");
}
byte[] U = new byte[hLen];
byte[] T = new byte[hLen];
byte[] block1 = new byte[S.length + 4];
int l = (int) Math.ceil((double) dkLen / hLen);
int r = dkLen - (l - 1) * hLen;
arraycopy(S, 0, block1, 0, S.length);
for (int i = 1; i <= l; i++) {
block1[S.length + 0] = (byte) (i >> 24 & 0xff);
block1[S.length + 1] = (byte) (i >> 16 & 0xff);
block1[S.length + 2] = (byte) (i >> 8 & 0xff);
block1[S.length + 3] = (byte) (i >> 0 & 0xff);
mac.update(block1);
mac.doFinal(U, 0);
arraycopy(U, 0, T, 0, hLen);
for (int j = 1; j < c; j++) {
mac.update(U);
mac.doFinal(U, 0);
for (int k = 0; k < hLen; k++) {
T[k] ^= U[k];
}
}
arraycopy(T, 0, DK, (i - 1) * hLen, (i == l ? r : hLen));
}
}
}
```
|
```package com.lambdaworks.crypto.test;
import com.lambdaworks.crypto.SCrypt;
import org.junit.Test;
import static org.junit.Assert.*;
import static com.lambdaworks.crypto.test.CryptoTestUtil.*;
import static com.lambdaworks.crypto.SCrypt.*;
public class SCryptTest {
@Test
public void scrypt_paper_appendix_b() throws Exception {
byte[] P, S;
int N, r, p, dkLen;
String DK;
// empty key & salt test missing because unsupported by JCE
P = "password".getBytes("UTF-8");
S = "NaCl".getBytes("UTF-8");
N = 1024;
r = 8;
p = 16;
dkLen = 64;
DK = "fdbabe1c9d3472007856e7190d01e9fe7c6ad7cbc8237830e77376634b3731622eaf30d92e22a3886ff109279d9830dac727afb94a83ee6d8360cbdfa2cc0640";
assertArrayEquals(decode(DK), SCrypt.scrypt(P, S, N, r, p, dkLen));
P = "pleaseletmein".getBytes("UTF-8");
S = "SodiumChloride".getBytes("UTF-8");
N = 16384;
r = 8;
p = 1;
dkLen = 64;
DK = "7023bdcb3afd7348461c06cd81fd38ebfda8fbba904f8e3ea9b543f6545da1f2d5432955613f0fcf62d49705242a9af9e61e85dc0d651e40dfcf017b45575887";
assertArrayEquals(decode(DK), scrypt(P, S, N, r, p, dkLen));
P = "pleaseletmein".getBytes("UTF-8");
S = "SodiumChloride".getBytes("UTF-8");
N = 1048576;
r = 8;
p = 1;
dkLen = 64;
DK = "2101cb9b6a511aaeaddbbe09cf70f881ec568d574a2ffd4dabe5ee9820adaa478e56fd8f4ba5d09ffa1c6d927c40f4c337304049e8a952fbcbf45c6fa77a41a4";
assertArrayEquals(decode(DK), SCrypt.scrypt(P, S, N, r, p, dkLen));
}
@Test(expected = IllegalArgumentException.class)
public void scrypt_invalid_N_zero() throws Exception {
byte[] P = "pleaseletmein".getBytes("UTF-8");
byte[] S = "SodiumChloride".getBytes("UTF-8");
scrypt(P, S, 0, 1, 1, 64);
}
@Test(expected = IllegalArgumentException.class)
public void scrypt_invalid_N_odd() throws Exception {
byte[] P = "pleaseletmein".getBytes("UTF-8");
byte[] S = "SodiumChloride".getBytes("UTF-8");
scrypt(P, S, 3, 1, 1, 64);
}
@Test(expected = IllegalArgumentException.class)
public void scrypt_invalid_N_large() throws Exception {
byte[] P = "pleaseletmein".getBytes("UTF-8");
byte[] S = "SodiumChloride".getBytes("UTF-8");
int r = 8;
int N = Integer.MAX_VALUE / 128;
scrypt(P, S, N, r, 1, 64);
}
// @Test(expected = IllegalArgumentException.class)
// public void scrypt_invalid_r_large() throws Exception {
// byte[] P = "pleaseletmein".getBytes("UTF-8");
// byte[] S = "SodiumChloride".getBytes("UTF-8");
// int N = 1024;
// int r = Integer.MAX_VALUE / 128 + 1;
// int p = 0;
// scrypt(P, S, N, r, p, 64);
// }
}
```
|
Please help me generate a test for this class.
|
```package com.lambdaworks.crypto;
import com.lambdaworks.jni.*;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.GeneralSecurityException;
import static java.lang.Integer.MAX_VALUE;
import static java.lang.System.arraycopy;
/**
* An implementation of the <a href="http://www.tarsnap.com/scrypt/scrypt.pdf"/>scrypt</a>
* key derivation function. This class will attempt to load a native library
* containing the optimized C implementation from
* <a href="http://www.tarsnap.com/scrypt.html">http://www.tarsnap.com/scrypt.html<a> and
* fall back to the pure Java version if that fails.
*
* @author Will Glozer
*/
public class SCrypt {
private static final boolean native_library_loaded;
static {
LibraryLoader loader = LibraryLoaders.loader();
native_library_loaded = loader.load("scrypt", true);
}
/**
* Implementation of the <a href="http://www.tarsnap.com/scrypt/scrypt.pdf"/>scrypt KDF</a>.
* Calls the native implementation {@link #scryptN} when the native library was successfully
* loaded, otherwise calls {@link #scryptJ}.
*
* @param passwd Password.
* @param salt Salt.
* @param N CPU cost parameter.
* @param r Memory cost parameter.
* @param p Parallelization parameter.
* @param dkLen Intended length of the derived key.
*
* @return The derived key.
*
* @throws GeneralSecurityException when HMAC_SHA256 is not available.
*/
public static byte[] scrypt(byte[] passwd, byte[] salt, int N, int r, int p, int dkLen) throws GeneralSecurityException {
return native_library_loaded ? scryptN(passwd, salt, N, r, p, dkLen) : scryptJ(passwd, salt, N, r, p, dkLen);
}
/**
* Native C implementation of the <a href="http://www.tarsnap.com/scrypt/scrypt.pdf"/>scrypt KDF</a> using
* the code from <a href="http://www.tarsnap.com/scrypt.html">http://www.tarsnap.com/scrypt.html<a>.
*
* @param passwd Password.
* @param salt Salt.
* @param N CPU cost parameter.
* @param r Memory cost parameter.
* @param p Parallelization parameter.
* @param dkLen Intended length of the derived key.
*
* @return The derived key.
*/
public static native byte[] scryptN(byte[] passwd, byte[] salt, int N, int r, int p, int dkLen);
/**
* Pure Java implementation of the <a href="http://www.tarsnap.com/scrypt/scrypt.pdf"/>scrypt KDF</a>.
*
* @param passwd Password.
* @param salt Salt.
* @param N CPU cost parameter.
* @param r Memory cost parameter.
* @param p Parallelization parameter.
* @param dkLen Intended length of the derived key.
*
* @return The derived key.
*
* @throws GeneralSecurityException when HMAC_SHA256 is not available.
*/
public static byte[] scryptJ(byte[] passwd, byte[] salt, int N, int r, int p, int dkLen) throws GeneralSecurityException {
if (N < 2 || (N & (N - 1)) != 0) throw new IllegalArgumentException("N must be a power of 2 greater than 1");
if (N > MAX_VALUE / 128 / r) throw new IllegalArgumentException("Parameter N is too large");
if (r > MAX_VALUE / 128 / p) throw new IllegalArgumentException("Parameter r is too large");
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(passwd, "HmacSHA256"));
byte[] DK = new byte[dkLen];
byte[] B = new byte[128 * r * p];
byte[] XY = new byte[256 * r];
byte[] V = new byte[128 * r * N];
int i;
PBKDF.pbkdf2(mac, salt, 1, B, p * 128 * r);
for (i = 0; i < p; i++) {
smix(B, i * 128 * r, r, N, V, XY);
}
PBKDF.pbkdf2(mac, B, 1, DK, dkLen);
return DK;
}
public static void smix(byte[] B, int Bi, int r, int N, byte[] V, byte[] XY) {
int Xi = 0;
int Yi = 128 * r;
int i;
arraycopy(B, Bi, XY, Xi, 128 * r);
for (i = 0; i < N; i++) {
arraycopy(XY, Xi, V, i * (128 * r), 128 * r);
blockmix_salsa8(XY, Xi, Yi, r);
}
for (i = 0; i < N; i++) {
int j = integerify(XY, Xi, r) & (N - 1);
blockxor(V, j * (128 * r), XY, Xi, 128 * r);
blockmix_salsa8(XY, Xi, Yi, r);
}
arraycopy(XY, Xi, B, Bi, 128 * r);
}
public static void blockmix_salsa8(byte[] BY, int Bi, int Yi, int r) {
byte[] X = new byte[64];
int i;
arraycopy(BY, Bi + (2 * r - 1) * 64, X, 0, 64);
for (i = 0; i < 2 * r; i++) {
blockxor(BY, i * 64, X, 0, 64);
salsa20_8(X);
arraycopy(X, 0, BY, Yi + (i * 64), 64);
}
for (i = 0; i < r; i++) {
arraycopy(BY, Yi + (i * 2) * 64, BY, Bi + (i * 64), 64);
}
for (i = 0; i < r; i++) {
arraycopy(BY, Yi + (i * 2 + 1) * 64, BY, Bi + (i + r) * 64, 64);
}
}
public static int R(int a, int b) {
return (a << b) | (a >>> (32 - b));
}
public static void salsa20_8(byte[] B) {
int[] B32 = new int[16];
int[] x = new int[16];
int i;
for (i = 0; i < 16; i++) {
B32[i] = (B[i * 4 + 0] & 0xff) << 0;
B32[i] |= (B[i * 4 + 1] & 0xff) << 8;
B32[i] |= (B[i * 4 + 2] & 0xff) << 16;
B32[i] |= (B[i * 4 + 3] & 0xff) << 24;
}
arraycopy(B32, 0, x, 0, 16);
for (i = 8; i > 0; i -= 2) {
x[ 4] ^= R(x[ 0]+x[12], 7); x[ 8] ^= R(x[ 4]+x[ 0], 9);
x[12] ^= R(x[ 8]+x[ 4],13); x[ 0] ^= R(x[12]+x[ 8],18);
x[ 9] ^= R(x[ 5]+x[ 1], 7); x[13] ^= R(x[ 9]+x[ 5], 9);
x[ 1] ^= R(x[13]+x[ 9],13); x[ 5] ^= R(x[ 1]+x[13],18);
x[14] ^= R(x[10]+x[ 6], 7); x[ 2] ^= R(x[14]+x[10], 9);
x[ 6] ^= R(x[ 2]+x[14],13); x[10] ^= R(x[ 6]+x[ 2],18);
x[ 3] ^= R(x[15]+x[11], 7); x[ 7] ^= R(x[ 3]+x[15], 9);
x[11] ^= R(x[ 7]+x[ 3],13); x[15] ^= R(x[11]+x[ 7],18);
x[ 1] ^= R(x[ 0]+x[ 3], 7); x[ 2] ^= R(x[ 1]+x[ 0], 9);
x[ 3] ^= R(x[ 2]+x[ 1],13); x[ 0] ^= R(x[ 3]+x[ 2],18);
x[ 6] ^= R(x[ 5]+x[ 4], 7); x[ 7] ^= R(x[ 6]+x[ 5], 9);
x[ 4] ^= R(x[ 7]+x[ 6],13); x[ 5] ^= R(x[ 4]+x[ 7],18);
x[11] ^= R(x[10]+x[ 9], 7); x[ 8] ^= R(x[11]+x[10], 9);
x[ 9] ^= R(x[ 8]+x[11],13); x[10] ^= R(x[ 9]+x[ 8],18);
x[12] ^= R(x[15]+x[14], 7); x[13] ^= R(x[12]+x[15], 9);
x[14] ^= R(x[13]+x[12],13); x[15] ^= R(x[14]+x[13],18);
}
for (i = 0; i < 16; ++i) B32[i] = x[i] + B32[i];
for (i = 0; i < 16; i++) {
B[i * 4 + 0] = (byte) (B32[i] >> 0 & 0xff);
B[i * 4 + 1] = (byte) (B32[i] >> 8 & 0xff);
B[i * 4 + 2] = (byte) (B32[i] >> 16 & 0xff);
B[i * 4 + 3] = (byte) (B32[i] >> 24 & 0xff);
}
}
public static void blockxor(byte[] S, int Si, byte[] D, int Di, int len) {
for (int i = 0; i < len; i++) {
D[Di + i] ^= S[Si + i];
}
}
public static int integerify(byte[] B, int Bi, int r) {
int n;
Bi += (2 * r - 1) * 64;
n = (B[Bi + 0] & 0xff) << 0;
n |= (B[Bi + 1] & 0xff) << 8;
n |= (B[Bi + 2] & 0xff) << 16;
n |= (B[Bi + 3] & 0xff) << 24;
return n;
}
}
```
|
```package com.lambdaworks.jni.test;
import com.lambdaworks.jni.Platform;
import com.lambdaworks.jni.UnsupportedPlatformException;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class PlatformTest extends AbstractPlatformDetectionTest {
@Test
public void arch() throws Exception {
assertEquals(Platform.Arch.x86_64, detectArch("x86_64").arch);
assertEquals(Platform.Arch.x86_64, detectArch("amd64").arch);
assertEquals(Platform.Arch.x86, detectArch("i386").arch);
}
@Test
public void os() throws Exception {
assertEquals(Platform.OS.darwin, detectOs("Mac OS X").os);
assertEquals(Platform.OS.darwin, detectOs("Darwin").os);
assertEquals(Platform.OS.freebsd, detectOs("FreeBSD").os);
assertEquals(Platform.OS.linux, detectOs("Linux").os);
}
@Test(expected = UnsupportedPlatformException.class)
public void unsupported() throws Exception {
setPlatform("PA-RISC", "MPE/iX");
Platform.detect();
}
}
```
|
Please help me generate a test for this class.
|
```package com.lambdaworks.jni;
import java.util.regex.Pattern;
import static java.lang.System.getProperty;
import static java.util.regex.Pattern.CASE_INSENSITIVE;
/**
* A platform is a unique combination of CPU architecture and operating system. This class
* attempts to determine the platform it is executing on by examining and normalizing the
* <code>os.arch</code> and <code>os.name</code> system properties.
*
* @author Will Glozer
*/
public class Platform {
public enum Arch {
x86 ("x86|i386"),
x86_64("x86_64|amd64");
Pattern pattern;
Arch(String pattern) {
this.pattern = Pattern.compile("\\A" + pattern + "\\Z", CASE_INSENSITIVE);
}
}
public enum OS {
darwin ("darwin|mac os x"),
freebsd("freebsd"),
linux ("linux");
Pattern pattern;
OS(String pattern) {
this.pattern = Pattern.compile("\\A" + pattern + "\\Z", CASE_INSENSITIVE);
}
}
public final Arch arch;
public final OS os;
private Platform(Arch arch, OS os) {
this.arch = arch;
this.os = os;
}
/**
* Attempt to detect the current platform.
*
* @return The current platform.
*
* @throws UnsupportedPlatformException if the platform cannot be detected.
*/
public static Platform detect() throws UnsupportedPlatformException {
String osArch = getProperty("os.arch");
String osName = getProperty("os.name");
for (Arch arch : Arch.values()) {
if (arch.pattern.matcher(osArch).matches()) {
for (OS os : OS.values()) {
if (os.pattern.matcher(osName).matches()) {
return new Platform(arch, os);
}
}
}
}
String msg = String.format("Unsupported platform %s %s", osArch, osName);
throw new UnsupportedPlatformException(msg);
}
}
```
|
```package com.lambdaworks.crypto.test;
import com.lambdaworks.codec.Base64;
import com.lambdaworks.crypto.SCryptUtil;
import org.junit.Assert;
import org.junit.Test;
import static org.junit.Assert.*;
public class SCryptUtilTest {
String passwd = "secret";
@Test
public void scrypt() {
int N = 16384;
int r = 8;
int p = 1;
String hashed = SCryptUtil.scrypt(passwd, N, r, p);
String[] parts = hashed.split("\\$");
assertEquals(5, parts.length);
assertEquals("s0", parts[1]);
Assert.assertEquals(16, Base64.decode(parts[3].toCharArray()).length);
assertEquals(32, Base64.decode(parts[4].toCharArray()).length);
int params = Integer.valueOf(parts[2], 16);
assertEquals(N, (int) Math.pow(2, params >> 16 & 0xffff));
assertEquals(r, params >> 8 & 0xff);
assertEquals(p, params >> 0 & 0xff);
}
@Test
public void check() {
String hashed = SCryptUtil.scrypt(passwd, 16384, 8, 1);
assertTrue(SCryptUtil.check(passwd, hashed));
assertFalse(SCryptUtil.check("s3cr3t", hashed));
}
@Test
public void format_0_rp_max() throws Exception {
int N = 2;
int r = 255;
int p = 255;
String hashed = SCryptUtil.scrypt(passwd, N, r, p);
assertTrue(SCryptUtil.check(passwd, hashed));
String[] parts = hashed.split("\\$");
int params = Integer.valueOf(parts[2], 16);
assertEquals(N, (int) Math.pow(2, params >>> 16 & 0xffff));
assertEquals(r, params >> 8 & 0xff);
assertEquals(p, params >> 0 & 0xff);
}
}
```
|
Please help me generate a test for this class.
|
```package com.lambdaworks.crypto;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
import static com.lambdaworks.codec.Base64.*;
/**
* Simple {@link SCrypt} interface for hashing passwords using the
* <a href="http://www.tarsnap.com/scrypt.html">scrypt</a> key derivation function
* and comparing a plain text password to a hashed one. The hashed output is an
* extended implementation of the Modular Crypt Format that also includes the scrypt
* algorithm parameters.
*
* Format: <code>$s0$PARAMS$SALT$KEY</code>.
*
* <dl>
* <dd>PARAMS</dd><dt>32-bit hex integer containing log2(N) (16 bits), r (8 bits), and p (8 bits)</dt>
* <dd>SALT</dd><dt>base64-encoded salt</dt>
* <dd>KEY</dd><dt>base64-encoded derived key</dt>
* </dl>
*
* <code>s0</code> identifies version 0 of the scrypt format, using a 128-bit salt and 256-bit derived key.
*
* @author Will Glozer
*/
public class SCryptUtil {
/**
* Hash the supplied plaintext password and generate output in the format described
* in {@link SCryptUtil}.
*
* @param passwd Password.
* @param N CPU cost parameter.
* @param r Memory cost parameter.
* @param p Parallelization parameter.
*
* @return The hashed password.
*/
public static String scrypt(String passwd, int N, int r, int p) {
try {
byte[] salt = new byte[16];
SecureRandom.getInstance("SHA1PRNG").nextBytes(salt);
byte[] derived = SCrypt.scrypt(passwd.getBytes("UTF-8"), salt, N, r, p, 32);
String params = Long.toString(log2(N) << 16L | r << 8 | p, 16);
StringBuilder sb = new StringBuilder((salt.length + derived.length) * 2);
sb.append("$s0$").append(params).append('$');
sb.append(encode(salt)).append('$');
sb.append(encode(derived));
return sb.toString();
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException("JVM doesn't support UTF-8?");
} catch (GeneralSecurityException e) {
throw new IllegalStateException("JVM doesn't support SHA1PRNG or HMAC_SHA256?");
}
}
/**
* Compare the supplied plaintext password to a hashed password.
*
* @param passwd Plaintext password.
* @param hashed scrypt hashed password.
*
* @return true if passwd matches hashed value.
*/
public static boolean check(String passwd, String hashed) {
try {
String[] parts = hashed.split("\\$");
if (parts.length != 5 || !parts[1].equals("s0")) {
throw new IllegalArgumentException("Invalid hashed value");
}
long params = Long.parseLong(parts[2], 16);
byte[] salt = decode(parts[3].toCharArray());
byte[] derived0 = decode(parts[4].toCharArray());
int N = (int) Math.pow(2, params >> 16 & 0xffff);
int r = (int) params >> 8 & 0xff;
int p = (int) params & 0xff;
byte[] derived1 = SCrypt.scrypt(passwd.getBytes("UTF-8"), salt, N, r, p, 32);
if (derived0.length != derived1.length) return false;
int result = 0;
for (int i = 0; i < derived0.length; i++) {
result |= derived0[i] ^ derived1[i];
}
return result == 0;
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException("JVM doesn't support UTF-8?");
} catch (GeneralSecurityException e) {
throw new IllegalStateException("JVM doesn't support SHA1PRNG or HMAC_SHA256?");
}
}
private static int log2(int n) {
int log = 0;
if ((n & 0xffff0000 ) != 0) { n >>>= 16; log = 16; }
if (n >= 256) { n >>>= 8; log += 8; }
if (n >= 16 ) { n >>>= 4; log += 4; }
if (n >= 4 ) { n >>>= 2; log += 2; }
return log + (n >>> 1);
}
}
```
|
```package com.lambdaworks.jni.test;
import com.lambdaworks.jni.*;
import org.junit.*;
import static java.lang.System.*;
import static org.junit.Assert.assertTrue;
public class LibraryLoadersTest {
private String vmSpec;
@Before
public final void saveProperties() {
vmSpec = getProperty("java.vm.specification.name");
}
@After
public final void restoreProperties() {
setProperty("java.vm.specification.name", vmSpec);
clearProperty("com.lambdaworks.jni.loader");
}
@Test
public void autoDetectLoader() throws Exception {
assertTrue(loader("Java") instanceof JarLibraryLoader);
assertTrue(loader("Dalvik") instanceof SysLibraryLoader);
}
@Test
public void overrideLoaderDetection() throws Exception {
assertTrue(loaderForName("jar") instanceof JarLibraryLoader);
assertTrue(loaderForName("nil") instanceof NilLibraryLoader);
assertTrue(loaderForName("sys") instanceof SysLibraryLoader);
}
@Test(expected = IllegalStateException.class)
public void invalidLoaderProperty() throws Exception {
loaderForName("invalid");
}
private LibraryLoader loader(String spec) {
setProperty("java.vm.specification.name", spec + " Virtual Machine Specification");
return LibraryLoaders.loader();
}
private LibraryLoader loaderForName(String name) {
setProperty("com.lambdaworks.jni.loader", name);
return LibraryLoaders.loader();
}
}
```
|
Please help me generate a test for this class.
|
```package com.lambdaworks.jni;
/**
* {@code LibraryLoaders} will create the appropriate {@link LibraryLoader} for
* the VM it is running on.
*
* The system property {@code com.lambdaworks.jni.loader} may be used to override
* loader auto-detection, or to disable loading native libraries entirely via use
* of the nil loader.
*
* @author Will Glozer
*/
public class LibraryLoaders {
/**
* Create a new {@link LibraryLoader} for the current VM.
*
* @return the loader.
*/
public static LibraryLoader loader() {
String type = System.getProperty("com.lambdaworks.jni.loader");
if (type != null) {
if (type.equals("sys")) return new SysLibraryLoader();
if (type.equals("nil")) return new NilLibraryLoader();
if (type.equals("jar")) return new JarLibraryLoader();
throw new IllegalStateException("Illegal value for com.lambdaworks.jni.loader: " + type);
}
String vmSpec = System.getProperty("java.vm.specification.name");
return vmSpec.startsWith("Java") ? new JarLibraryLoader() : new SysLibraryLoader();
}
}
```
|