index
int64 0
0
| repo_id
stringlengths 26
205
| file_path
stringlengths 51
246
| content
stringlengths 8
433k
| __index_level_0__
int64 0
10k
|
---|---|---|---|---|
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/properties/JobsMemoryPropertiesTest.java
|
/*
*
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.properties;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* Unit tests for the properties holder class.
*
* @author tgianos
* @since 3.0.0
*/
class JobsMemoryPropertiesTest {
private JobsMemoryProperties properties;
/**
* Setup for tests.
*/
@BeforeEach
void setup() {
this.properties = new JobsMemoryProperties();
}
/**
* Make sure we have the default properties.
*/
@Test
void hasDefaultProperties() {
Assertions.assertThat(this.properties.getDefaultJobMemory()).isEqualTo(1_024);
Assertions.assertThat(this.properties.getMaxJobMemory()).isEqualTo(10_240);
Assertions.assertThat(this.properties.getMaxSystemMemory()).isEqualTo(30_720);
}
/**
* Make sure can set the default job memory.
*/
@Test
void canSetDefaultJobMemory() {
final int memory = 1_512;
this.properties.setDefaultJobMemory(memory);
Assertions.assertThat(this.properties.getDefaultJobMemory()).isEqualTo(memory);
}
/**
* Make sure can set the max job memory.
*/
@Test
void canSetMaxJobMemory() {
final int memory = 1_512;
this.properties.setMaxJobMemory(memory);
Assertions.assertThat(this.properties.getMaxJobMemory()).isEqualTo(memory);
}
/**
* Make sure can set the max system memory.
*/
@Test
void canSetMaxSystemMemory() {
final int memory = 1_512;
this.properties.setMaxSystemMemory(memory);
Assertions.assertThat(this.properties.getMaxSystemMemory()).isEqualTo(memory);
}
}
| 2,400 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/properties/DatabaseCleanupPropertiesTest.java
|
/*
*
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.properties;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.UUID;
/**
* Unit tests for {@link DatabaseCleanupProperties}.
*
* @author tgianos
* @since 3.0.0
*/
class DatabaseCleanupPropertiesTest {
private DatabaseCleanupProperties properties;
@BeforeEach
void setup() {
this.properties = new DatabaseCleanupProperties();
}
@Test
void canGetDefaultValues() {
Assertions.assertThat(this.properties.isEnabled()).isFalse();
Assertions.assertThat(this.properties.getExpression()).isEqualTo("0 0 0 * * *");
Assertions.assertThat(this.properties.getBatchSize()).isEqualTo(10_000);
Assertions.assertThat(this.properties.getApplicationCleanup().isSkip()).isFalse();
Assertions.assertThat(this.properties.getCommandCleanup().isSkip()).isFalse();
Assertions.assertThat(this.properties.getCommandDeactivation().isSkip()).isFalse();
Assertions.assertThat(this.properties.getCommandDeactivation().getCommandCreationThreshold()).isEqualTo(60);
Assertions.assertThat(this.properties.getJobCleanup().isSkip()).isFalse();
Assertions.assertThat(this.properties.getJobCleanup().getRetention()).isEqualTo(90);
Assertions.assertThat(this.properties.getJobCleanup().getMaxDeletedPerTransaction()).isEqualTo(1000);
Assertions.assertThat(this.properties.getJobCleanup().getPageSize()).isEqualTo(1000);
Assertions.assertThat(this.properties.getClusterCleanup().isSkip()).isFalse();
Assertions.assertThat(this.properties.getTagCleanup().isSkip()).isFalse();
Assertions.assertThat(this.properties.getFileCleanup().isSkip()).isFalse();
Assertions.assertThat(this.properties.getFileCleanup().getBatchDaysWithin()).isEqualTo(30);
Assertions.assertThat(this.properties.getFileCleanup().getRollingWindowHours()).isEqualTo(12);
}
@Test
void canEnable() {
this.properties.setEnabled(true);
Assertions.assertThat(this.properties.isEnabled()).isTrue();
}
@Test
void canSetExpression() {
final String expression = UUID.randomUUID().toString();
this.properties.setExpression(expression);
Assertions.assertThat(this.properties.getExpression()).isEqualTo(expression);
}
@Test
void canSetBatchSize() {
final int batchSize = 123;
this.properties.setBatchSize(batchSize);
Assertions.assertThat(this.properties.getBatchSize()).isEqualTo(batchSize);
}
@Test
void canSetJobCleanupRetention() {
final int retention = 2318;
this.properties.getJobCleanup().setRetention(retention);
Assertions.assertThat(this.properties.getJobCleanup().getRetention()).isEqualTo(retention);
}
@Test
void canSetJobCleanupMaxDeletedPerTransaction() {
final int max = 2318;
this.properties.getJobCleanup().setMaxDeletedPerTransaction(max);
Assertions.assertThat(this.properties.getJobCleanup().getMaxDeletedPerTransaction()).isEqualTo(max);
}
@Test
void canSetJobCleanupPageSize() {
final int size = 2318;
this.properties.getJobCleanup().setPageSize(size);
Assertions.assertThat(this.properties.getJobCleanup().getPageSize()).isEqualTo(size);
}
@Test
void canSetSkipJobCleanup() {
this.properties.getJobCleanup().setSkip(true);
Assertions.assertThat(this.properties.getJobCleanup().isSkip()).isTrue();
}
@Test
void canSetSkipClusterCleanup() {
this.properties.getClusterCleanup().setSkip(true);
Assertions.assertThat(this.properties.getClusterCleanup().isSkip()).isTrue();
}
@Test
void canSetSkipTagsCleanup() {
this.properties.getTagCleanup().setSkip(true);
Assertions.assertThat(this.properties.getTagCleanup().isSkip()).isTrue();
}
@Test
void caSetSkipFilesCleanup() {
this.properties.getFileCleanup().setSkip(true);
Assertions.assertThat(this.properties.getFileCleanup().isSkip()).isTrue();
}
@Test
void canSetSkipApplicationsCleanup() {
this.properties.getApplicationCleanup().setSkip(true);
Assertions.assertThat(this.properties.getApplicationCleanup().isSkip()).isTrue();
}
@Test
void canEnableSkipCommandsCleanup() {
this.properties.getCommandCleanup().setSkip(true);
Assertions.assertThat(this.properties.getCommandCleanup().isSkip()).isTrue();
}
@Test
void canEnableSkipCommandDeactivation() {
this.properties.getCommandDeactivation().setSkip(true);
Assertions.assertThat(this.properties.getCommandDeactivation().isSkip()).isTrue();
}
@Test
void canSetCommandDeactivationCommandCreationThreshold() {
final int newThreshold = this.properties.getCommandDeactivation().getCommandCreationThreshold() + 1;
this.properties.getCommandDeactivation().setCommandCreationThreshold(newThreshold);
Assertions
.assertThat(this.properties.getCommandDeactivation().getCommandCreationThreshold())
.isEqualTo(newThreshold);
}
}
| 2,401 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/properties/JobsForwardingPropertiesTest.java
|
/*
*
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.properties;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.UUID;
/**
* Unit tests for JobForwardingProperties.
*
* @author tgianos
* @since 3.0.0
*/
class JobsForwardingPropertiesTest {
private JobsForwardingProperties properties;
/**
* Setup for the tests.
*/
@BeforeEach
void setup() {
this.properties = new JobsForwardingProperties();
}
/**
* Test to make sure default constructor sets default values.
*/
@Test
void hasDefaultValues() {
Assertions.assertThat(this.properties.isEnabled()).isFalse();
Assertions.assertThat(this.properties.getScheme()).isEqualTo("http");
Assertions.assertThat(this.properties.getPort()).isEqualTo(8080);
}
/**
* Make sure setting the enabled property is persisted.
*/
@Test
void canEnable() {
this.properties.setEnabled(true);
Assertions.assertThat(this.properties.isEnabled()).isTrue();
}
/**
* Make sure setting the scheme property is persisted.
*/
@Test
void canSetScheme() {
final String scheme = UUID.randomUUID().toString();
this.properties.setScheme(scheme);
Assertions.assertThat(this.properties.getScheme()).isEqualTo(scheme);
}
/**
* Make sure setting the port property is persisted.
*/
@Test
void canSetPort() {
final int port = 443;
this.properties.setPort(port);
Assertions.assertThat(this.properties.getPort()).isEqualTo(port);
}
}
| 2,402 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/properties/JobsPropertiesTest.java
|
/*
*
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.properties;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
/**
* Unit tests for the JobsProperties class.
*
* @author tgianos
* @since 3.0.0
*/
class JobsPropertiesTest {
private JobsMemoryProperties memory;
private JobsForwardingProperties forwarding;
private JobsLocationsProperties locations;
private JobsUsersProperties users;
private JobsActiveLimitProperties activeLimit;
private JobsProperties properties;
/**
* Setup for the tests.
*/
@BeforeEach
void setup() {
this.memory = Mockito.mock(JobsMemoryProperties.class);
this.forwarding = Mockito.mock(JobsForwardingProperties.class);
this.locations = Mockito.mock(JobsLocationsProperties.class);
this.users = Mockito.mock(JobsUsersProperties.class);
this.activeLimit = Mockito.mock(JobsActiveLimitProperties.class);
this.properties = new JobsProperties(
this.forwarding,
this.locations,
this.memory,
this.users,
this.activeLimit
);
}
/**
* Make sure we can construct.
*/
@Test
void canConstruct() {
Assertions.assertThat(this.properties.getMemory()).isNotNull();
Assertions.assertThat(this.properties.getForwarding()).isNotNull();
Assertions.assertThat(this.properties.getLocations()).isNotNull();
Assertions.assertThat(this.properties.getUsers()).isNotNull();
Assertions.assertThat(this.properties.getActiveLimit()).isNotNull();
}
/**
* Make sure all the setters work.
*/
@Test
void canSet() {
Assertions
.assertThatCode(
() -> {
this.properties.setForwarding(this.forwarding);
this.properties.setLocations(this.locations);
this.properties.setMemory(this.memory);
this.properties.setUsers(this.users);
this.properties.setActiveLimit(this.activeLimit);
}
)
.doesNotThrowAnyException();
}
}
| 2,403 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/properties/JobsActiveLimitPropertiesTest.java
|
/*
*
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.properties;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.core.env.Environment;
/**
* Unit tests for JobsActiveLimitProperties.
*
* @author mprimi
* @since 3.1.0
*/
class JobsActiveLimitPropertiesTest {
private JobsActiveLimitProperties properties;
/**
* Setup for the tests.
*/
@BeforeEach
void setup() {
this.properties = new JobsActiveLimitProperties();
}
/**
* Make sure the constructor sets defaults.
*/
@Test
void canConstruct() {
Assertions.assertThat(this.properties.isEnabled()).isEqualTo(JobsActiveLimitProperties.DEFAULT_ENABLED);
Assertions.assertThat(this.properties.getCount()).isEqualTo(JobsActiveLimitProperties.DEFAULT_COUNT);
Assertions
.assertThat(this.properties.getUserLimit("SomeUser"))
.isEqualTo(JobsActiveLimitProperties.DEFAULT_COUNT);
}
/**
* Make sure we can set the enabled field.
*/
@Test
void canSetEnabled() {
final boolean newEnabledValue = !this.properties.isEnabled();
this.properties.setEnabled(newEnabledValue);
Assertions.assertThat(this.properties.isEnabled()).isEqualTo(newEnabledValue);
}
/**
* Make sure we can set the count field.
*/
@Test
void canSetRunAsEnabled() {
final int newCountValue = 2 * this.properties.getCount();
this.properties.setCount(newCountValue);
Assertions.assertThat(this.properties.getCount()).isEqualTo(newCountValue);
}
/**
* Make sure environment is used when looking for a user-specific limit override.
*/
@Test
void testUserOverrides() {
final String userName = "SomeUser";
final int userLimit = 999;
final Environment environment = Mockito.mock(Environment.class);
Mockito
.when(environment.getProperty(
JobsActiveLimitProperties.USER_LIMIT_OVERRIDE_PROPERTY_PREFIX + userName,
Integer.class,
this.properties.getCount())
)
.thenReturn(userLimit);
this.properties.setEnvironment(environment);
Assertions.assertThat(this.properties.getUserLimit(userName)).isEqualTo(userLimit);
}
}
| 2,404 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/properties/JobsLocationsPropertiesTest.java
|
/*
*
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.properties;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.net.URI;
import java.util.UUID;
/**
* Unit tests for {@link JobsLocationsProperties}.
*
* @author tgianos
* @since 3.0.0
*/
class JobsLocationsPropertiesTest {
private static final String SYSTEM_TMP_DIR = System.getProperty("java.io.tmpdir", "/tmp/");
private JobsLocationsProperties properties;
/**
* Setup for the tests.
*/
@BeforeEach
void setup() {
this.properties = new JobsLocationsProperties();
}
/**
* Make sure defaults are set.
*/
@Test
void canConstruct() {
Assertions
.assertThat(this.properties.getArchives())
.isEqualTo(URI.create("file://" + (SYSTEM_TMP_DIR.endsWith("/")
? SYSTEM_TMP_DIR
: SYSTEM_TMP_DIR + "/") + "genie/archives/"));
Assertions
.assertThat(this.properties.getJobs())
.isEqualTo(URI.create("file://" + (SYSTEM_TMP_DIR.endsWith("/")
? SYSTEM_TMP_DIR
: SYSTEM_TMP_DIR + "/") + "genie/jobs/"));
}
/**
* Test setting the archives location.
*/
@Test
void canSetArchivesLocation() {
final URI location = URI.create("file:/" + UUID.randomUUID().toString());
this.properties.setArchives(location);
Assertions.assertThat(this.properties.getArchives()).isEqualTo(location);
}
/**
* Test setting the jobs dir location.
*/
@Test
void canSetJobsLocation() {
final URI location = URI.create("file:/" + UUID.randomUUID().toString());
this.properties.setJobs(location);
Assertions.assertThat(this.properties.getJobs()).isEqualTo(location);
}
}
| 2,405 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/properties/JobsUsersPropertiesTest.java
|
/*
*
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.properties;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* Unit tests for JobsUsersProperties.
*
* @author tgianos
* @since 3.0.0
*/
class JobsUsersPropertiesTest {
private JobsUsersProperties properties;
/**
* Setup for the tests.
*/
@BeforeEach
void setup() {
this.properties = new JobsUsersProperties();
}
/**
* Make sure we can set the run as user field.
*/
@Test
void canSetRunAsEnabled() {
this.properties.setRunAsUserEnabled(true);
Assertions.assertThat(this.properties.isRunAsUserEnabled()).isTrue();
}
}
| 2,406 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/properties/JobResolutionPropertiesTest.java
|
/*
*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.properties;
import com.netflix.genie.common.internal.dtos.ComputeResources;
import com.netflix.genie.common.internal.dtos.Image;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.mock.env.MockEnvironment;
import org.springframework.util.unit.DataSize;
import java.util.List;
import java.util.Map;
/**
* Tests for {@link JobResolutionProperties}.
*
* @author tgianos
* @since 4.3.0
*/
class JobResolutionPropertiesTest {
private MockEnvironment environment;
@BeforeEach
void setup() {
this.environment = new MockEnvironment();
}
@Test
void defaultsSetProperly() {
final JobResolutionProperties properties = new JobResolutionProperties(this.environment);
Assertions
.assertThat(properties.getDefaultComputeResources())
.isNotNull();
final ComputeResources computeResources = properties.getDefaultComputeResources();
Assertions.assertThat(computeResources.getCpu()).contains(1);
Assertions.assertThat(computeResources.getGpu()).contains(0);
Assertions.assertThat(computeResources.getMemoryMb()).contains(1_500L);
Assertions.assertThat(computeResources.getDiskMb()).contains(DataSize.ofGigabytes(10L).toMegabytes());
Assertions
.assertThat(computeResources.getNetworkMbps())
.contains(DataSize.ofMegabytes(1_250L).toMegabytes() * 8);
Assertions
.assertThat(properties.getDefaultImages())
.isNotNull()
.isEmpty();
}
@Test
void computeResourcesOverriddenProperly() {
this.environment
.withProperty("genie.services.resolution.defaults.runtime.resources.cpu", "7")
.withProperty("genie.services.resolution.defaults.runtime.resources.gpu", "1")
.withProperty("genie.services.resolution.defaults.runtime.resources.memory", "1GB")
.withProperty("genie.services.resolution.defaults.runtime.resources.disk", "100GB")
.withProperty("genie.services.resolution.defaults.runtime.resources.network", "15GB");
final JobResolutionProperties properties = new JobResolutionProperties(this.environment);
Assertions
.assertThat(properties.getDefaultComputeResources())
.isNotNull();
final ComputeResources computeResources = properties.getDefaultComputeResources();
Assertions.assertThat(computeResources.getCpu()).contains(7);
Assertions.assertThat(computeResources.getGpu()).contains(1);
Assertions.assertThat(computeResources.getMemoryMb()).contains(DataSize.ofGigabytes(1L).toMegabytes());
Assertions.assertThat(computeResources.getDiskMb()).contains(DataSize.ofGigabytes(100L).toMegabytes());
Assertions
.assertThat(computeResources.getNetworkMbps())
.contains(DataSize.ofGigabytes(15L).toMegabytes() * 8);
Assertions
.assertThat(properties.getDefaultImages())
.isNotNull()
.isEmpty();
}
@Test
void defaultImagesOverriddenProperly() {
this.environment
.withProperty("genie.services.resolution.defaults.runtime.images.genie.name", "genie-agent")
.withProperty("genie.services.resolution.defaults.runtime.images.genie.tag", "4.3.0")
.withProperty("genie.services.resolution.defaults.runtime.images.genie.arguments[0]", "hi")
.withProperty("genie.services.resolution.defaults.runtime.images.genie.arguments[1]", "bye")
.withProperty("genie.services.resolution.defaults.runtime.images.python.tag", "3.10.0")
.withProperty("genie.services.resolution.defaults.runtime.images.python.arguments[0]", "pip")
.withProperty("genie.services.resolution.defaults.runtime.images.python.arguments[1]", "freeze");
final JobResolutionProperties properties = new JobResolutionProperties(this.environment);
Assertions
.assertThat(properties.getDefaultComputeResources())
.isNotNull();
final Map<String, Image> defaultImages = properties.getDefaultImages();
Assertions
.assertThat(defaultImages)
.isNotNull()
.containsKey("genie")
.containsKey("python");
final Image genieAgent = defaultImages.get("genie");
Assertions.assertThat(genieAgent).isNotNull();
Assertions.assertThat(genieAgent.getName()).contains("genie-agent");
Assertions.assertThat(genieAgent.getTag()).contains("4.3.0");
Assertions.assertThat(genieAgent.getArguments()).isNotNull().isEqualTo(List.of("hi", "bye"));
final Image python = defaultImages.get("python");
Assertions.assertThat(python).isNotNull();
Assertions.assertThat(python.getName()).isEmpty();
Assertions.assertThat(python.getTag()).contains("3.10.0");
Assertions.assertThat(python.getArguments()).isNotNull().isEqualTo(List.of("pip", "freeze"));
}
@Test
void refreshWorksProperly() {
final JobResolutionProperties properties = new JobResolutionProperties(this.environment);
Assertions
.assertThat(properties.getDefaultComputeResources())
.isNotNull();
ComputeResources computeResources = properties.getDefaultComputeResources();
Assertions.assertThat(computeResources.getCpu()).contains(1);
this.environment.withProperty("genie.services.resolution.defaults.runtime.resources.cpu", "3");
properties.refresh();
computeResources = properties.getDefaultComputeResources();
Assertions.assertThat(computeResources.getCpu()).contains(3);
}
}
| 2,407 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/properties/package-info.java
|
/*
*
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Tests for properties clases.
*
* @author tgianos
* @since 3.0.0
*/
package com.netflix.genie.web.properties;
| 2,408 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/data/services/impl
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/data/services/impl/jpa/JpaPersistenceServiceImplApplicationsTest.java
|
/*
*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.data.services.impl.jpa;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.netflix.genie.common.internal.dtos.Application;
import com.netflix.genie.common.internal.dtos.ApplicationMetadata;
import com.netflix.genie.common.internal.dtos.ApplicationRequest;
import com.netflix.genie.common.internal.dtos.ApplicationStatus;
import com.netflix.genie.common.internal.dtos.ExecutionEnvironment;
import com.netflix.genie.common.internal.tracing.brave.BraveTracingComponents;
import com.netflix.genie.web.data.services.impl.jpa.entities.ApplicationEntity;
import com.netflix.genie.web.data.services.impl.jpa.entities.CommandEntity;
import com.netflix.genie.web.data.services.impl.jpa.repositories.JpaApplicationRepository;
import com.netflix.genie.web.data.services.impl.jpa.repositories.JpaRepositories;
import com.netflix.genie.web.exceptions.checked.IdAlreadyExistsException;
import com.netflix.genie.web.exceptions.checked.NotFoundException;
import com.netflix.genie.web.exceptions.checked.PreconditionFailedException;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.dao.DuplicateKeyException;
import javax.persistence.EntityManager;
import java.time.Instant;
import java.util.Optional;
import java.util.UUID;
/**
* Tests for the applications persistence APIs of {@link JpaPersistenceServiceImpl}.
*
* @author tgianos
*/
class JpaPersistenceServiceImplApplicationsTest {
private static final String APP_1_ID = "app1";
private static final String APP_1_NAME = "tez";
private static final String APP_1_USER = "tgianos";
private static final String APP_1_VERSION = "1.2.3";
private JpaApplicationRepository jpaApplicationRepository;
private JpaPersistenceServiceImpl persistenceService;
@BeforeEach
void setup() {
this.jpaApplicationRepository = Mockito.mock(JpaApplicationRepository.class);
final JpaRepositories jpaRepositories = Mockito.mock(JpaRepositories.class);
Mockito.when(jpaRepositories.getApplicationRepository()).thenReturn(this.jpaApplicationRepository);
this.persistenceService = new JpaPersistenceServiceImpl(
Mockito.mock(EntityManager.class),
jpaRepositories,
Mockito.mock(BraveTracingComponents.class)
);
}
@Test
void testGetApplicationNotExists() {
final String id = UUID.randomUUID().toString();
Mockito.when(this.jpaApplicationRepository.getApplicationDto(id)).thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.persistenceService.getApplication(id));
}
@Test
void testCreateApplicationAlreadyExists() {
final ApplicationRequest request = new ApplicationRequest.Builder(
new ApplicationMetadata.Builder(
APP_1_NAME,
APP_1_USER,
APP_1_VERSION,
ApplicationStatus.ACTIVE
)
.build()
)
.withRequestedId(APP_1_ID)
.build();
Mockito
.when(this.jpaApplicationRepository.save(Mockito.any(ApplicationEntity.class)))
.thenThrow(new DuplicateKeyException("Duplicate Key"));
Assertions
.assertThatExceptionOfType(IdAlreadyExistsException.class)
.isThrownBy(() -> this.persistenceService.saveApplication(request));
}
@Test
void testUpdateApplicationNoAppExists() {
final Application app = new Application(
APP_1_ID,
Instant.now(),
Instant.now(),
new ExecutionEnvironment(null, null, null),
new ApplicationMetadata.Builder(
APP_1_NAME,
APP_1_USER,
APP_1_VERSION,
ApplicationStatus.ACTIVE
)
.build()
);
Mockito.when(this.jpaApplicationRepository.getApplicationDto(APP_1_ID)).thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.persistenceService.updateApplication(APP_1_ID, app));
}
@Test
void testUpdateApplicationIdsDontMatch() {
final String id = UUID.randomUUID().toString();
final Application app = new Application(
UUID.randomUUID().toString(),
Instant.now(),
Instant.now(),
new ExecutionEnvironment(null, null, null),
new ApplicationMetadata.Builder(
APP_1_NAME,
APP_1_USER,
APP_1_VERSION,
ApplicationStatus.ACTIVE
)
.build()
);
Mockito.when(this.jpaApplicationRepository.existsByUniqueId(id)).thenReturn(true);
Assertions
.assertThatExceptionOfType(PreconditionFailedException.class)
.isThrownBy(() -> this.persistenceService.updateApplication(id, app));
}
@Test
void testDeleteAllBlocked() {
final ApplicationEntity applicationEntity = Mockito.mock(ApplicationEntity.class);
final CommandEntity commandEntity = Mockito.mock(CommandEntity.class);
Mockito.when(this.jpaApplicationRepository.findAll()).thenReturn(Lists.newArrayList(applicationEntity));
Mockito.when(applicationEntity.getCommands()).thenReturn(Sets.newHashSet(commandEntity));
Assertions
.assertThatExceptionOfType(PreconditionFailedException.class)
.isThrownBy(() -> this.persistenceService.deleteAllApplications());
}
@Test
void testAddConfigsToApplicationNoApp() {
final String id = UUID.randomUUID().toString();
Mockito.when(this.jpaApplicationRepository.findByUniqueId(Mockito.eq(id))).thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.persistenceService.addConfigsToResource(id, Sets.newHashSet(), Application.class));
}
@Test
void testUpdateConfigsForApplicationNoApp() {
final String id = UUID.randomUUID().toString();
Mockito.when(this.jpaApplicationRepository.findByUniqueId(Mockito.eq(id))).thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(
() -> this.persistenceService.updateConfigsForResource(id, Sets.newHashSet(), Application.class)
);
}
@Test
void testGetConfigsForApplicationNoApp() {
final String id = UUID.randomUUID().toString();
Mockito.when(this.jpaApplicationRepository.findByUniqueId(id)).thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.persistenceService.getConfigsForResource(id, Application.class));
}
@Test
void testRemoveAllConfigsForApplicationNoApp() {
final String id = UUID.randomUUID().toString();
Mockito.when(this.jpaApplicationRepository.findByUniqueId(id)).thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.persistenceService.removeAllConfigsForResource(id, Application.class));
}
@Test
void testRemoveConfigForApplicationNoApp() {
final String id = UUID.randomUUID().toString();
Mockito.when(this.jpaApplicationRepository.findByUniqueId(id)).thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.persistenceService.removeConfigForResource(id, "something", Application.class));
}
@Test
void testAddDependenciesForApplicationNoApp() {
final String id = UUID.randomUUID().toString();
Mockito.when(this.jpaApplicationRepository.findByUniqueId(id)).thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(
() -> this.persistenceService.addDependenciesToResource(id, Sets.newHashSet(), Application.class)
);
}
@Test
void testUpdateDependenciesForApplicationNoApp() {
final String id = UUID.randomUUID().toString();
Mockito.when(this.jpaApplicationRepository.findByUniqueId(id)).thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(
() -> this.persistenceService.updateDependenciesForResource(id, Sets.newHashSet(), Application.class)
);
}
@Test
void testGetDependenciesForApplicationNoApp() {
final String id = UUID.randomUUID().toString();
Mockito.when(this.jpaApplicationRepository.findByUniqueId(id)).thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.persistenceService.getDependenciesForResource(id, Application.class));
}
@Test
void testRemoveAllDependenciesForApplicationNoApp() {
final String id = UUID.randomUUID().toString();
Mockito.when(this.jpaApplicationRepository.findByUniqueId(id)).thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.persistenceService.removeAllDependenciesForResource(id, Application.class));
}
@Test
void testRemoveDependencyForApplicationNoApp() {
final String id = UUID.randomUUID().toString();
Mockito.when(this.jpaApplicationRepository.findByUniqueId(id)).thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.persistenceService.removeDependencyForResource(id, "something", Application.class));
}
@Test
void testAddTagsForApplicationNoApp() {
final String id = UUID.randomUUID().toString();
Mockito.when(this.jpaApplicationRepository.findByUniqueId(id)).thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.persistenceService.addTagsToResource(id, Sets.newHashSet(), Application.class));
}
@Test
void testUpdateTagsForApplicationNoApp() {
final String id = UUID.randomUUID().toString();
Mockito.when(this.jpaApplicationRepository.findByUniqueId(id)).thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.persistenceService.updateTagsForResource(id, Sets.newHashSet(), Application.class));
}
@Test
void testGetTagsForApplicationNoApp() {
final String id = UUID.randomUUID().toString();
Mockito.when(this.jpaApplicationRepository.findByUniqueId(id)).thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.persistenceService.getTagsForResource(id, Application.class));
}
@Test
void testRemoveAllTagsForApplicationNoApp() {
final String id = UUID.randomUUID().toString();
Mockito.when(this.jpaApplicationRepository.findByUniqueId(id)).thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.persistenceService.removeAllTagsForResource(id, Application.class));
}
@Test
void testRemoveTagForApplicationNoApp() {
final String id = UUID.randomUUID().toString();
Mockito.when(this.jpaApplicationRepository.findByUniqueId(id)).thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.persistenceService.removeTagForResource(id, "something", Application.class));
}
@Test
void testGetCommandsForApplicationNoApp() {
final String id = UUID.randomUUID().toString();
Mockito.when(this.jpaApplicationRepository.findByUniqueId(id)).thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.persistenceService.getCommandsForApplication(id, null));
}
}
| 2,409 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/data/services/impl
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/data/services/impl/jpa/JpaPersistenceServiceImplJobsTest.java
|
/*
*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.data.services.impl.jpa;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.netflix.genie.common.dto.Job;
import com.netflix.genie.common.dto.UserResourcesSummary;
import com.netflix.genie.common.exceptions.GenieException;
import com.netflix.genie.common.exceptions.GenieNotFoundException;
import com.netflix.genie.common.internal.dtos.AgentClientMetadata;
import com.netflix.genie.common.internal.dtos.ArchiveStatus;
import com.netflix.genie.common.internal.dtos.JobSpecification;
import com.netflix.genie.common.internal.dtos.JobStatus;
import com.netflix.genie.common.internal.exceptions.checked.GenieCheckedException;
import com.netflix.genie.common.internal.exceptions.unchecked.GenieInvalidStatusException;
import com.netflix.genie.common.internal.exceptions.unchecked.GenieJobAlreadyClaimedException;
import com.netflix.genie.common.internal.tracing.brave.BraveTracingComponents;
import com.netflix.genie.web.data.services.impl.jpa.entities.ClusterEntity;
import com.netflix.genie.web.data.services.impl.jpa.entities.CommandEntity;
import com.netflix.genie.web.data.services.impl.jpa.entities.JobEntity;
import com.netflix.genie.web.data.services.impl.jpa.queries.aggregates.UserJobResourcesAggregate;
import com.netflix.genie.web.data.services.impl.jpa.queries.projections.JobApiProjection;
import com.netflix.genie.web.data.services.impl.jpa.queries.projections.JobApplicationsProjection;
import com.netflix.genie.web.data.services.impl.jpa.queries.projections.JobCommandProjection;
import com.netflix.genie.web.data.services.impl.jpa.queries.projections.JobProjection;
import com.netflix.genie.web.data.services.impl.jpa.queries.projections.v4.FinishedJobProjection;
import com.netflix.genie.web.data.services.impl.jpa.queries.projections.v4.JobRequestProjection;
import com.netflix.genie.web.data.services.impl.jpa.queries.projections.v4.JobSpecificationProjection;
import com.netflix.genie.web.data.services.impl.jpa.repositories.JpaApplicationRepository;
import com.netflix.genie.web.data.services.impl.jpa.repositories.JpaClusterRepository;
import com.netflix.genie.web.data.services.impl.jpa.repositories.JpaCommandRepository;
import com.netflix.genie.web.data.services.impl.jpa.repositories.JpaFileRepository;
import com.netflix.genie.web.data.services.impl.jpa.repositories.JpaJobRepository;
import com.netflix.genie.web.data.services.impl.jpa.repositories.JpaRepositories;
import com.netflix.genie.web.data.services.impl.jpa.repositories.JpaTagRepository;
import com.netflix.genie.web.dtos.ResolvedJob;
import com.netflix.genie.web.exceptions.checked.NotFoundException;
import org.apache.commons.lang3.StringUtils;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import javax.persistence.EntityManager;
import java.time.Instant;
import java.util.HashMap;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
/**
* Tests for the {@link JpaPersistenceServiceImpl} class focusing on the job related APIs.
*
* @author tgianos
* @since 3.0.0
*/
class JpaPersistenceServiceImplJobsTest {
// TODO the use of a static converter makes this class hard to test. Switch to a non-static converter object.
private JpaJobRepository jobRepository;
private JpaApplicationRepository applicationRepository;
private JpaClusterRepository clusterRepository;
private JpaCommandRepository commandRepository;
private JpaPersistenceServiceImpl persistenceService;
@BeforeEach
void setup() {
this.jobRepository = Mockito.mock(JpaJobRepository.class);
this.applicationRepository = Mockito.mock(JpaApplicationRepository.class);
this.clusterRepository = Mockito.mock(JpaClusterRepository.class);
this.commandRepository = Mockito.mock(JpaCommandRepository.class);
final JpaTagRepository tagRepository = Mockito.mock(JpaTagRepository.class);
final JpaFileRepository fileRepository = Mockito.mock(JpaFileRepository.class);
final JpaRepositories jpaRepositories = Mockito.mock(JpaRepositories.class);
Mockito.when(jpaRepositories.getApplicationRepository()).thenReturn(this.applicationRepository);
Mockito.when(jpaRepositories.getClusterRepository()).thenReturn(this.clusterRepository);
Mockito.when(jpaRepositories.getCommandRepository()).thenReturn(this.commandRepository);
Mockito.when(jpaRepositories.getJobRepository()).thenReturn(this.jobRepository);
Mockito.when(jpaRepositories.getFileRepository()).thenReturn(fileRepository);
Mockito.when(jpaRepositories.getTagRepository()).thenReturn(tagRepository);
this.persistenceService = new JpaPersistenceServiceImpl(
Mockito.mock(EntityManager.class),
jpaRepositories,
Mockito.mock(BraveTracingComponents.class)
);
}
@Test
void noJobRequestFoundReturnsEmptyOptional() {
Mockito
.when(this.jobRepository.findByUniqueId(Mockito.anyString(), Mockito.eq(JobRequestProjection.class)))
.thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.persistenceService.getJobRequest(UUID.randomUUID().toString()));
}
@Test
void noJobUnableToSaveResolvedJob() {
Mockito
.when(this.jobRepository.findByUniqueId(Mockito.anyString()))
.thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(
() -> this.persistenceService.saveResolvedJob(
UUID.randomUUID().toString(),
Mockito.mock(ResolvedJob.class)
)
);
}
@Test
void jobAlreadyResolvedDoesNotResolvedInformationAgain() throws GenieCheckedException {
final JobEntity jobEntity = Mockito.mock(JobEntity.class);
Mockito
.when(this.jobRepository.findByUniqueId(Mockito.anyString()))
.thenReturn(Optional.of(jobEntity));
Mockito.when(jobEntity.isResolved()).thenReturn(true);
this.persistenceService.saveResolvedJob(UUID.randomUUID().toString(), Mockito.mock(ResolvedJob.class));
Mockito.verify(jobEntity, Mockito.never()).setCluster(Mockito.any(ClusterEntity.class));
}
@Test
void jobAlreadyTerminalDoesNotSaveResolvedJob() throws GenieCheckedException {
final JobEntity jobEntity = Mockito.mock(JobEntity.class);
Mockito
.when(this.jobRepository.findByUniqueId(Mockito.anyString()))
.thenReturn(Optional.of(jobEntity));
Mockito.when(jobEntity.isResolved()).thenReturn(false);
Mockito.when(jobEntity.getStatus()).thenReturn(JobStatus.KILLED.name());
this.persistenceService.saveResolvedJob(UUID.randomUUID().toString(), Mockito.mock(ResolvedJob.class));
Mockito.verify(jobEntity, Mockito.never()).setCluster(Mockito.any(ClusterEntity.class));
}
@Test
void noResourceToSaveForResolvedJob() {
final String jobId = UUID.randomUUID().toString();
final JobEntity jobEntity = Mockito.mock(JobEntity.class);
Mockito.when(jobEntity.isResolved()).thenReturn(false);
Mockito.when(jobEntity.getStatus()).thenReturn(JobStatus.RESERVED.name());
final String clusterId = UUID.randomUUID().toString();
final ClusterEntity clusterEntity = Mockito.mock(ClusterEntity.class);
final JobSpecification.ExecutionResource clusterResource
= Mockito.mock(JobSpecification.ExecutionResource.class);
Mockito.when(clusterResource.getId()).thenReturn(clusterId);
final String commandId = UUID.randomUUID().toString();
final CommandEntity commandEntity = Mockito.mock(CommandEntity.class);
final JobSpecification.ExecutionResource commandResource
= Mockito.mock(JobSpecification.ExecutionResource.class);
Mockito.when(commandResource.getId()).thenReturn(commandId);
final String applicationId = UUID.randomUUID().toString();
final JobSpecification.ExecutionResource applicationResource
= Mockito.mock(JobSpecification.ExecutionResource.class);
Mockito.when(applicationResource.getId()).thenReturn(applicationId);
final ResolvedJob resolvedJob = Mockito.mock(ResolvedJob.class);
final JobSpecification jobSpecification = Mockito.mock(JobSpecification.class);
Mockito.when(resolvedJob.getJobSpecification()).thenReturn(jobSpecification);
Mockito.when(jobSpecification.getCluster()).thenReturn(clusterResource);
Mockito.when(jobSpecification.getCommand()).thenReturn(commandResource);
Mockito
.when(jobSpecification.getApplications())
.thenReturn(Lists.newArrayList(applicationResource));
Mockito
.when(this.jobRepository.findByUniqueId(jobId))
.thenReturn(Optional.of(jobEntity));
Mockito
.when(this.clusterRepository.findByUniqueId(clusterId))
.thenReturn(Optional.empty())
.thenReturn(Optional.of(clusterEntity))
.thenReturn(Optional.of(clusterEntity));
Mockito
.when(this.commandRepository.findByUniqueId(commandId))
.thenReturn(Optional.empty())
.thenReturn(Optional.of(commandEntity));
Mockito.when(this.applicationRepository.findByUniqueId(applicationId)).thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.persistenceService.saveResolvedJob(jobId, resolvedJob));
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.persistenceService.saveResolvedJob(jobId, resolvedJob));
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.persistenceService.saveResolvedJob(jobId, resolvedJob));
}
@Test
void noJobUnableToGetJobSpecification() {
Mockito
.when(this.jobRepository.findByUniqueId(Mockito.anyString(), Mockito.eq(JobSpecificationProjection.class)))
.thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.persistenceService.getJobSpecification(UUID.randomUUID().toString()));
}
@Test
void unresolvedJobReturnsEmptyJobSpecificationOptional() throws GenieCheckedException {
final JobEntity jobEntity = Mockito.mock(JobEntity.class);
Mockito
.when(this.jobRepository.getJobSpecification(Mockito.anyString()))
.thenReturn(Optional.of(jobEntity));
Mockito.when(jobEntity.isResolved()).thenReturn(false);
Assertions
.assertThat(this.persistenceService.getJobSpecification(UUID.randomUUID().toString()))
.isNotPresent();
}
@Test
void testClaimJobErrorCases() {
Mockito
.when(this.jobRepository.findByUniqueId(Mockito.anyString()))
.thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(
() -> this.persistenceService.claimJob(
UUID.randomUUID().toString(),
Mockito.mock(AgentClientMetadata.class)
)
);
final JobEntity jobEntity = Mockito.mock(JobEntity.class);
final String id = UUID.randomUUID().toString();
Mockito
.when(this.jobRepository.findByUniqueId(id))
.thenReturn(Optional.of(jobEntity));
Mockito.when(jobEntity.isClaimed()).thenReturn(true);
Assertions
.assertThatExceptionOfType(GenieJobAlreadyClaimedException.class)
.isThrownBy(() -> this.persistenceService.claimJob(id, Mockito.mock(AgentClientMetadata.class)));
Mockito.when(jobEntity.isClaimed()).thenReturn(false);
Mockito.when(jobEntity.getStatus()).thenReturn(JobStatus.INVALID.name());
Assertions
.assertThatExceptionOfType(GenieInvalidStatusException.class)
.isThrownBy(() -> this.persistenceService.claimJob(id, Mockito.mock(AgentClientMetadata.class)));
}
@Test
void testClaimJobValidBehavior() throws GenieCheckedException {
final JobEntity jobEntity = Mockito.mock(JobEntity.class);
final AgentClientMetadata agentClientMetadata = Mockito.mock(AgentClientMetadata.class);
final String id = UUID.randomUUID().toString();
Mockito.when(this.jobRepository.findByUniqueId(id)).thenReturn(Optional.of(jobEntity));
Mockito.when(jobEntity.isClaimed()).thenReturn(false);
Mockito.when(jobEntity.getStatus()).thenReturn(JobStatus.RESOLVED.name());
final String agentHostname = UUID.randomUUID().toString();
Mockito.when(agentClientMetadata.getHostname()).thenReturn(Optional.of(agentHostname));
final String agentVersion = UUID.randomUUID().toString();
Mockito.when(agentClientMetadata.getVersion()).thenReturn(Optional.of(agentVersion));
final int agentPid = 238;
Mockito.when(agentClientMetadata.getPid()).thenReturn(Optional.of(agentPid));
this.persistenceService.claimJob(id, agentClientMetadata);
Mockito.verify(jobEntity, Mockito.times(1)).setClaimed(true);
Mockito.verify(jobEntity, Mockito.times(1)).setStatus(JobStatus.CLAIMED.name());
Mockito.verify(jobEntity, Mockito.times(1)).setAgentHostname(agentHostname);
Mockito.verify(jobEntity, Mockito.times(1)).setAgentVersion(agentVersion);
Mockito.verify(jobEntity, Mockito.times(1)).setAgentPid(agentPid);
}
@Test
void testUpdateJobStatusErrorCases() throws NotFoundException {
final String id = UUID.randomUUID().toString();
Assertions
.assertThat(this.persistenceService.updateJobStatus(id, JobStatus.CLAIMED, JobStatus.CLAIMED, null))
.isEqualTo(JobStatus.CLAIMED);
Mockito
.when(this.jobRepository.findByUniqueId(id))
.thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.persistenceService.updateJobStatus(
id,
JobStatus.CLAIMED,
JobStatus.INIT,
null
)
);
final JobEntity jobEntity = Mockito.mock(JobEntity.class);
Mockito
.when(this.jobRepository.findByUniqueId(id))
.thenReturn(Optional.of(jobEntity));
Mockito.when(jobEntity.getStatus()).thenReturn(JobStatus.INIT.name());
Assertions
.assertThat(this.persistenceService.updateJobStatus(id, JobStatus.CLAIMED, JobStatus.INIT, null))
.isEqualTo(JobStatus.INIT);
}
@Test
void testUpdateJobValidBehavior() throws GenieCheckedException {
final String id = UUID.randomUUID().toString();
final String newStatusMessage = UUID.randomUUID().toString();
final JobEntity jobEntity = Mockito.mock(JobEntity.class);
Mockito.when(this.jobRepository.findByUniqueId(id)).thenReturn(Optional.of(jobEntity));
Mockito.when(jobEntity.getStatus()).thenReturn(JobStatus.INIT.name());
this.persistenceService.updateJobStatus(id, JobStatus.INIT, JobStatus.RUNNING, newStatusMessage);
Mockito.verify(jobEntity, Mockito.times(1)).setStatus(JobStatus.RUNNING.name());
Mockito.verify(jobEntity, Mockito.times(1)).setStatusMsg(newStatusMessage);
Mockito.verify(jobEntity, Mockito.times(1)).setStarted(Mockito.any(Instant.class));
final String finalStatusMessage = UUID.randomUUID().toString();
Mockito.when(jobEntity.getStatus()).thenReturn(JobStatus.RUNNING.name());
Mockito.when(jobEntity.getStarted()).thenReturn(Optional.of(Instant.now()));
this.persistenceService.updateJobStatus(id, JobStatus.RUNNING, JobStatus.SUCCEEDED, finalStatusMessage);
Mockito.verify(jobEntity, Mockito.times(1)).setStatus(JobStatus.SUCCEEDED.name());
Mockito.verify(jobEntity, Mockito.times(1)).setStatusMsg(finalStatusMessage);
Mockito.verify(jobEntity, Mockito.times(1)).setFinished(Mockito.any(Instant.class));
}
@Test
void testGetJobStatus() throws GenieCheckedException {
final String id = UUID.randomUUID().toString();
final JobStatus status = JobStatus.RUNNING;
Mockito
.when(this.jobRepository.getJobStatus(id))
.thenReturn(Optional.empty())
.thenReturn(Optional.of(status.name()));
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.persistenceService.getJobStatus(id));
Assertions.assertThat(this.persistenceService.getJobStatus(id)).isEqualByComparingTo(status);
}
@Test
void testGetFinishedJobNonExisting() {
final String id = UUID.randomUUID().toString();
Mockito
.when(this.jobRepository.findByUniqueId(id, FinishedJobProjection.class))
.thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.persistenceService.getFinishedJob(id));
}
// TODO: JpaJobPersistenceServiceImpl#getFinishedJob(String) for job in non-final state
// TODO: JpaJobPersistenceServiceImpl#getFinishedJob(String) successful
@Test
void testIsApiJobNoJob() {
final String id = UUID.randomUUID().toString();
Mockito
.when(this.jobRepository.findByUniqueId(id, JobApiProjection.class))
.thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.persistenceService.isApiJob(id));
}
@Test
void cantGetJobIfDoesNotExist() {
final String id = UUID.randomUUID().toString();
Mockito.when(this.jobRepository.findByUniqueId(id, JobProjection.class)).thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(GenieNotFoundException.class)
.isThrownBy(() -> this.persistenceService.getJob(id));
}
@Test
void canGetJob() throws GenieException {
final JobEntity jobEntity = new JobEntity();
final String id = UUID.randomUUID().toString();
jobEntity.setStatus(com.netflix.genie.common.dto.JobStatus.RUNNING.name());
jobEntity.setUniqueId(id);
Mockito.when(this.jobRepository.getV3Job(id)).thenReturn(Optional.of(jobEntity));
final Job returnedJob = this.persistenceService.getJob(id);
Mockito
.verify(this.jobRepository, Mockito.times(1))
.getV3Job(id);
Assertions.assertThat(returnedJob.getId()).isPresent().contains(id);
}
@Test
void cantGetJobClusterIfJobDoesNotExist() {
final String id = UUID.randomUUID().toString();
Mockito.when(this.jobRepository.getJobCluster(id)).thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.persistenceService.getJobCluster(id));
}
@Test
void cantGetJobClusterIfClusterDoesNotExist() {
final String id = UUID.randomUUID().toString();
final JobEntity entity = Mockito.mock(JobEntity.class);
Mockito.when(entity.getCluster()).thenReturn(Optional.empty());
Mockito.when(this.jobRepository.getJobCluster(id)).thenReturn(Optional.of(entity));
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.persistenceService.getJobCluster(id));
}
@Test
void cantGetJobCommandIfJobDoesNotExist() {
final String id = UUID.randomUUID().toString();
Mockito.when(this.jobRepository.findByUniqueId(id, JobCommandProjection.class)).thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.persistenceService.getJobCommand(id));
}
@Test
void cantGetJobCommandIfCommandDoesNotExist() {
final String id = UUID.randomUUID().toString();
final JobEntity entity = Mockito.mock(JobEntity.class);
Mockito.when(entity.getCommand()).thenReturn(Optional.empty());
Mockito.when(this.jobRepository.findByUniqueId(id, JobCommandProjection.class)).thenReturn(Optional.of(entity));
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.persistenceService.getJobCommand(id));
}
@Test
void cantGetJobApplicationsIfJobDoesNotExist() {
final String id = UUID.randomUUID().toString();
Mockito
.when(this.jobRepository.findByUniqueId(id, JobApplicationsProjection.class))
.thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.persistenceService.getJobApplications(id));
}
@Test
void canGetJobApplications() throws GenieCheckedException {
final String id = UUID.randomUUID().toString();
final JobEntity entity = Mockito.mock(JobEntity.class);
Mockito.when(entity.getApplications()).thenReturn(Lists.newArrayList());
Mockito
.when(this.jobRepository.getJobApplications(id))
.thenReturn(Optional.of(entity))
.thenReturn(Optional.empty());
Assertions.assertThat(this.persistenceService.getJobApplications(id)).isEmpty();
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.persistenceService.getJobApplications(id));
}
@Test
void cantGetJobHostIfNoJobExecution() {
final String jobId = UUID.randomUUID().toString();
Mockito
.when(this.jobRepository.getJobHostname(jobId))
.thenReturn(Optional.empty());
}
@Test
void canGetJobHost() {
final String jobId = UUID.randomUUID().toString();
final String hostName = UUID.randomUUID().toString();
Mockito
.when(this.jobRepository.getJobHostname(jobId))
.thenReturn(Optional.of(hostName));
}
@Test
void canGetUserResourceSummariesNoRecords() {
Mockito
.when(this.jobRepository.getUserJobResourcesAggregates(JpaPersistenceServiceImpl.ACTIVE_STATUS_SET, true))
.thenReturn(Sets.newHashSet());
Assertions
.assertThat(this.persistenceService.getUserResourcesSummaries(JobStatus.getActiveStatuses(), true))
.isEmpty();
}
@Test
void canGetUserResourceSummaries() {
final UserJobResourcesAggregate p1 = Mockito.mock(UserJobResourcesAggregate.class);
final UserJobResourcesAggregate p2 = Mockito.mock(UserJobResourcesAggregate.class);
Mockito.when(p1.getUser()).thenReturn("foo");
Mockito.when(p1.getRunningJobsCount()).thenReturn(3L);
Mockito.when(p1.getUsedMemory()).thenReturn(1024L);
Mockito.when(p2.getUser()).thenReturn("bar");
Mockito.when(p2.getRunningJobsCount()).thenReturn(5L);
Mockito.when(p2.getUsedMemory()).thenReturn(2048L);
final Set<JobStatus> statuses = JobStatus.getResolvableStatuses();
final Set<String> statusStrings = statuses.stream().map(JobStatus::name).collect(Collectors.toSet());
Mockito
.when(this.jobRepository.getUserJobResourcesAggregates(statusStrings, false))
.thenReturn(Sets.newHashSet(p1, p2));
final HashMap<String, UserResourcesSummary> expectedMap = Maps.newHashMap();
expectedMap.put("foo", new UserResourcesSummary("foo", 3, 1024));
expectedMap.put("bar", new UserResourcesSummary("bar", 5, 2048));
Assertions
.assertThat(this.persistenceService.getUserResourcesSummaries(statuses, false))
.isEqualTo(expectedMap);
}
@Test
void canGetUsedMemoryOnHost() {
final String hostname = UUID.randomUUID().toString();
final long totalMemory = 213_328L;
Mockito
.when(this.jobRepository.getTotalMemoryUsedOnHost(hostname, JpaPersistenceServiceImpl.USING_MEMORY_JOB_SET))
.thenReturn(totalMemory);
Assertions.assertThat(this.persistenceService.getUsedMemoryOnHost(hostname)).isEqualTo(totalMemory);
}
@Test
void canGetActiveAgentJobs() {
final String job1Id = UUID.randomUUID().toString();
final String job2Id = UUID.randomUUID().toString();
Mockito
.when(this.jobRepository.getJobIdsWithStatusIn(JpaPersistenceServiceImpl.ACTIVE_STATUS_SET))
.thenReturn(Sets.newHashSet(job1Id, job2Id));
Assertions
.assertThat(this.persistenceService.getActiveJobs())
.isEqualTo(Sets.newHashSet(job1Id, job2Id));
}
@Test
void canGetActiveAgentJobsWhenEmpty() {
Mockito
.when(this.jobRepository.getJobIdsWithStatusIn(JpaPersistenceServiceImpl.ACTIVE_STATUS_SET))
.thenReturn(Sets.newHashSet());
Assertions
.assertThat(this.persistenceService.getActiveJobs())
.isEqualTo(Sets.newHashSet());
}
@Test
void canGetUnclaimedAgentJobs() {
final String jobId1 = UUID.randomUUID().toString();
final String jobId2 = UUID.randomUUID().toString();
Mockito
.when(this.jobRepository.getJobIdsWithStatusIn(JpaPersistenceServiceImpl.UNCLAIMED_STATUS_SET))
.thenReturn(Sets.newHashSet(jobId1, jobId2));
Assertions
.assertThat(this.persistenceService.getUnclaimedJobs())
.isEqualTo(Sets.newHashSet(jobId1, jobId2));
}
@Test
void canGetUnclaimedAgentJobsWhenEmpty() {
Mockito
.when(this.jobRepository.getJobIdsWithStatusIn(JpaPersistenceServiceImpl.UNCLAIMED_STATUS_SET))
.thenReturn(Sets.newHashSet());
Assertions
.assertThat(this.persistenceService.getUnclaimedJobs())
.isEqualTo(Sets.newHashSet());
}
@Test
void testUpdateJobStatusWithTooLongMessage() throws GenieCheckedException {
final String id = UUID.randomUUID().toString();
final JobEntity jobEntity = new JobEntity();
jobEntity.setStatus(JobStatus.INIT.name());
final String tooLong = StringUtils.leftPad("a", 256, 'b');
Mockito.when(this.jobRepository.findByUniqueId(id)).thenReturn(Optional.of(jobEntity));
this.persistenceService.updateJobStatus(id, JobStatus.INIT, JobStatus.RUNNING, tooLong);
Assertions.assertThat(jobEntity.getStatus()).isEqualTo(JobStatus.RUNNING.name());
Assertions.assertThat(jobEntity.getStatusMsg()).isPresent().contains(StringUtils.truncate(tooLong, 255));
}
@Test
void testGetJobsWithStatusAndArchiveStatusUpdatedBefore() {
Mockito
.when(
this.jobRepository.getJobsWithStatusAndArchiveStatusUpdatedBefore(
Mockito.anySet(),
Mockito.anySet(),
Mockito.any(Instant.class)
))
.thenReturn(Sets.newHashSet());
this.persistenceService.getJobsWithStatusAndArchiveStatusUpdatedBefore(
Sets.newHashSet(JobStatus.FAILED, JobStatus.KILLED),
Sets.newHashSet(ArchiveStatus.FAILED),
Instant.now()
);
}
}
| 2,410 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/data/services/impl
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/data/services/impl/jpa/JpaPersistenceServiceImplCommandsTest.java
|
/*
*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.data.services.impl.jpa;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.netflix.genie.common.internal.dtos.Command;
import com.netflix.genie.common.internal.dtos.CommandMetadata;
import com.netflix.genie.common.internal.dtos.CommandRequest;
import com.netflix.genie.common.internal.dtos.CommandStatus;
import com.netflix.genie.common.internal.dtos.ExecutionEnvironment;
import com.netflix.genie.common.internal.tracing.brave.BraveTracingComponents;
import com.netflix.genie.web.data.services.impl.jpa.entities.CommandEntity;
import com.netflix.genie.web.data.services.impl.jpa.repositories.JpaApplicationRepository;
import com.netflix.genie.web.data.services.impl.jpa.repositories.JpaCommandRepository;
import com.netflix.genie.web.data.services.impl.jpa.repositories.JpaCriterionRepository;
import com.netflix.genie.web.data.services.impl.jpa.repositories.JpaRepositories;
import com.netflix.genie.web.exceptions.checked.IdAlreadyExistsException;
import com.netflix.genie.web.exceptions.checked.NotFoundException;
import com.netflix.genie.web.exceptions.checked.PreconditionFailedException;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.dao.DuplicateKeyException;
import javax.persistence.EntityManager;
import java.time.Instant;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
/**
* Tests for the {@link JpaPersistenceServiceImpl} command specific functionality.
*
* @author tgianos
* @since 2.0.0
*/
class JpaPersistenceServiceImplCommandsTest {
private static final String COMMAND_1_ID = "command1";
private static final String COMMAND_1_NAME = "pig_13_prod";
private static final String COMMAND_1_USER = "tgianos";
private static final String COMMAND_1_VERSION = "1.2.3";
private static final List<String> COMMAND_1_EXECUTABLE = Lists.newArrayList("pig");
private static final String COMMAND_2_ID = "command2";
private JpaPersistenceServiceImpl service;
private JpaCommandRepository jpaCommandRepository;
private JpaApplicationRepository jpaApplicationRepository;
@BeforeEach
void setup() {
this.jpaCommandRepository = Mockito.mock(JpaCommandRepository.class);
this.jpaApplicationRepository = Mockito.mock(JpaApplicationRepository.class);
final JpaRepositories jpaRepositories = Mockito.mock(JpaRepositories.class);
Mockito.when(jpaRepositories.getApplicationRepository()).thenReturn(this.jpaApplicationRepository);
Mockito.when(jpaRepositories.getCommandRepository()).thenReturn(this.jpaCommandRepository);
Mockito.when(jpaRepositories.getCriterionRepository()).thenReturn(Mockito.mock(JpaCriterionRepository.class));
this.service = new JpaPersistenceServiceImpl(
Mockito.mock(EntityManager.class),
jpaRepositories,
Mockito.mock(BraveTracingComponents.class)
);
}
@Test
void testGetCommandNotExists() {
final String id = UUID.randomUUID().toString();
Mockito.when(this.jpaCommandRepository.getCommandDto(id)).thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.service.getCommand(id));
}
@Test
void testCreateCommandAlreadyExists() {
final CommandRequest command = new CommandRequest.Builder(
new CommandMetadata.Builder(
COMMAND_1_NAME,
COMMAND_1_USER,
COMMAND_1_VERSION,
CommandStatus.ACTIVE
)
.build(),
COMMAND_1_EXECUTABLE
)
.withRequestedId(COMMAND_1_ID)
.build();
Mockito
.when(this.jpaCommandRepository.save(Mockito.any(CommandEntity.class)))
.thenThrow(new DuplicateKeyException("Duplicate Key"));
Assertions
.assertThatExceptionOfType(IdAlreadyExistsException.class)
.isThrownBy(() -> this.service.saveCommand(command));
}
@Test
void testUpdateCommandNoCommandExists() {
final String id = UUID.randomUUID().toString();
Mockito.when(this.jpaCommandRepository.getCommandDto(id)).thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(
() -> this.service.updateCommand(
id,
new Command(
id,
Instant.now(),
Instant.now(),
new ExecutionEnvironment(null, null, null),
new CommandMetadata.Builder(
" ",
" ",
" ",
CommandStatus.ACTIVE
).build(),
Lists.newArrayList(UUID.randomUUID().toString()),
null,
null,
null
)
)
);
}
@Test
void testUpdateCommandIdsDontMatch() {
final Command command = Mockito.mock(Command.class);
Mockito.when(command.getId()).thenReturn(UUID.randomUUID().toString());
Assertions
.assertThatExceptionOfType(PreconditionFailedException.class)
.isThrownBy(() -> this.service.updateCommand(COMMAND_2_ID, command));
}
@Test
void testAddConfigsToCommandNoCommand() {
final String id = UUID.randomUUID().toString();
Mockito.when(this.jpaCommandRepository.findByUniqueId(id)).thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.service.addConfigsToResource(id, Sets.newHashSet(), Command.class));
}
@Test
void testUpdateConfigsForCommandNoCommand() {
final String id = UUID.randomUUID().toString();
Mockito.when(this.jpaCommandRepository.findByUniqueId(id)).thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.service.updateConfigsForResource(id, Sets.newHashSet(), Command.class));
}
@Test
void testGetConfigsForCommandNoCommand() {
final String id = UUID.randomUUID().toString();
Mockito.when(this.jpaCommandRepository.findByUniqueId(id)).thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.service.getConfigsForResource(id, Command.class));
}
@Test
void testRemoveAllConfigsForCommandNoCommand() {
final String id = UUID.randomUUID().toString();
Mockito.when(this.jpaCommandRepository.findByUniqueId(id)).thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.service.removeAllConfigsForResource(id, Command.class));
}
@Test
void testRemoveConfigForCommandNoCommand() {
final String id = UUID.randomUUID().toString();
Mockito.when(this.jpaCommandRepository.findByUniqueId(id)).thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.service.removeConfigForResource(id, "something", Command.class));
}
@Test
void testAddDependenciesForCommand() {
final String id = UUID.randomUUID().toString();
Mockito.when(this.jpaCommandRepository.findByUniqueId(id)).thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.service.addDependenciesToResource(id, Sets.newHashSet(), Command.class));
}
@Test
void testUpdateDependenciesForCommand() {
final String id = UUID.randomUUID().toString();
Mockito.when(this.jpaCommandRepository.findByUniqueId(id)).thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.service.updateDependenciesForResource(id, Sets.newHashSet(), Command.class));
}
@Test
void testGetDependenciesForCommand() {
final String id = UUID.randomUUID().toString();
Mockito.when(this.jpaCommandRepository.findByUniqueId(id)).thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.service.getDependenciesForResource(id, Command.class));
}
@Test
void testRemoveAllDependenciesForCommand() {
final String id = UUID.randomUUID().toString();
Mockito.when(this.jpaCommandRepository.findByUniqueId(id)).thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.service.removeAllDependenciesForResource(id, Command.class));
}
@Test
void testRemoveDependencyForCommand() {
final String id = UUID.randomUUID().toString();
Mockito.when(this.jpaCommandRepository.findByUniqueId(id)).thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.service.removeDependencyForResource(id, "something", Command.class));
}
@Test
void testSetApplicationsForCommandNoAppId() {
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(
() -> this.service.setApplicationsForCommand(
COMMAND_2_ID,
Lists.newArrayList(UUID.randomUUID().toString())
)
);
}
@Test
void testSetApplicationsForCommandNoCommandExists() {
final String id = UUID.randomUUID().toString();
Mockito.when(this.jpaCommandRepository.findByUniqueId(id)).thenReturn(Optional.empty());
Mockito.when(this.jpaApplicationRepository.existsByUniqueId(Mockito.anyString())).thenReturn(true);
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(
() -> this.service.setApplicationsForCommand(id, Lists.newArrayList(UUID.randomUUID().toString()))
);
}
@Test
void testSetApplicationsForCommandNoAppExists() {
final String appId = UUID.randomUUID().toString();
Mockito.when(this.jpaApplicationRepository.existsByUniqueId(appId)).thenReturn(false);
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.service.setApplicationsForCommand(COMMAND_2_ID, Lists.newArrayList(appId)));
}
@Test
void cantUpdateApplicationsForCommandWithDuplicates() {
final String appId1 = UUID.randomUUID().toString();
final String appId2 = UUID.randomUUID().toString();
final List<String> appIds = Lists.newArrayList(appId1, appId2, appId1);
Assertions
.assertThatExceptionOfType(PreconditionFailedException.class)
.isThrownBy(() -> this.service.setApplicationsForCommand(COMMAND_1_ID, appIds));
}
@Test
void testGetApplicationsForCommandNoCommand() {
final String id = UUID.randomUUID().toString();
Mockito.when(this.jpaCommandRepository.findByUniqueId(id)).thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.service.getApplicationsForCommand(id));
}
@Test
void testRemoveApplicationsForCommandNoCommandExists() {
final String id = UUID.randomUUID().toString();
Mockito.when(this.jpaCommandRepository.findByUniqueId(id)).thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.service.removeApplicationsForCommand(id));
}
@Test
void testAddTagsForCommandNoCommand() {
final String id = UUID.randomUUID().toString();
Mockito.when(this.jpaCommandRepository.findByUniqueId(id)).thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.service.addTagsToResource(id, Sets.newHashSet(), Command.class));
}
@Test
void testUpdateTagsForCommandNoCommand() {
final String id = UUID.randomUUID().toString();
Mockito.when(this.jpaCommandRepository.findByUniqueId(id)).thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.service.updateTagsForResource(id, Sets.newHashSet(), Command.class));
}
@Test
void testGetTagsForCommandNoCommand() {
final String id = UUID.randomUUID().toString();
Mockito.when(this.jpaCommandRepository.findByUniqueId(id)).thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.service.getTagsForResource(id, Command.class));
}
@Test
void testRemoveAllTagsForCommandNoCommand() {
final String id = UUID.randomUUID().toString();
Mockito.when(this.jpaCommandRepository.findByUniqueId(id)).thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.service.removeAllTagsForResource(id, Command.class));
}
@Test
void testRemoveTagForCommandNoCommand() {
final String id = UUID.randomUUID().toString();
Mockito.when(this.jpaCommandRepository.findByUniqueId(id)).thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.service.removeTagForResource(id, "something", Command.class));
}
@Test
void testGetClustersForCommandNoCommand() {
final String id = UUID.randomUUID().toString();
Mockito.when(this.jpaCommandRepository.findByUniqueId(id)).thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.service.getClustersForCommand(id, null));
}
}
| 2,411 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/data/services/impl
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/data/services/impl/jpa/JpaPersistenceServiceImplClustersTest.java
|
/*
*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.data.services.impl.jpa;
import com.google.common.collect.Sets;
import com.netflix.genie.common.internal.dtos.Cluster;
import com.netflix.genie.common.internal.dtos.ClusterMetadata;
import com.netflix.genie.common.internal.dtos.ClusterRequest;
import com.netflix.genie.common.internal.dtos.ClusterStatus;
import com.netflix.genie.common.internal.dtos.ExecutionEnvironment;
import com.netflix.genie.common.internal.tracing.brave.BraveTracingComponents;
import com.netflix.genie.web.data.services.impl.jpa.entities.ClusterEntity;
import com.netflix.genie.web.data.services.impl.jpa.entities.FileEntity;
import com.netflix.genie.web.data.services.impl.jpa.repositories.JpaClusterRepository;
import com.netflix.genie.web.data.services.impl.jpa.repositories.JpaFileRepository;
import com.netflix.genie.web.data.services.impl.jpa.repositories.JpaRepositories;
import com.netflix.genie.web.exceptions.checked.IdAlreadyExistsException;
import com.netflix.genie.web.exceptions.checked.NotFoundException;
import com.netflix.genie.web.exceptions.checked.PreconditionFailedException;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.dao.DuplicateKeyException;
import javax.persistence.EntityManager;
import java.time.Instant;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
/**
* Tests for the {@link JpaPersistenceServiceImpl} focusing on cluster functionality.
*
* @author tgianos
* @since 2.0.0
*/
class JpaPersistenceServiceImplClustersTest {
private static final String CLUSTER_1_ID = "cluster1";
private static final String CLUSTER_1_USER = "tgianos";
private static final String CLUSTER_1_NAME = "h2prod";
private static final String CLUSTER_1_VERSION = "2.4.0";
private JpaPersistenceServiceImpl service;
private JpaClusterRepository jpaClusterRepository;
private JpaFileRepository jpaFileRepository;
@BeforeEach
void setup() {
this.jpaClusterRepository = Mockito.mock(JpaClusterRepository.class);
this.jpaFileRepository = Mockito.mock(JpaFileRepository.class);
final JpaRepositories jpaRepositories = Mockito.mock(JpaRepositories.class);
Mockito.when(jpaRepositories.getClusterRepository()).thenReturn(this.jpaClusterRepository);
Mockito.when(jpaRepositories.getFileRepository()).thenReturn(this.jpaFileRepository);
this.service = new JpaPersistenceServiceImpl(
Mockito.mock(EntityManager.class),
jpaRepositories,
Mockito.mock(BraveTracingComponents.class)
);
}
@Test
void testGetClusterNotExists() {
final String id = UUID.randomUUID().toString();
Mockito.when(this.jpaClusterRepository.findByUniqueId(id)).thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.service.getCluster(id));
}
@Test
void testCreateClusterAlreadyExists() {
final Set<String> configs = Sets.newHashSet("a config", "another config", "yet another config");
final ClusterRequest request = new ClusterRequest.Builder(
new ClusterMetadata.Builder(
CLUSTER_1_NAME,
CLUSTER_1_USER,
CLUSTER_1_VERSION,
ClusterStatus.OUT_OF_SERVICE
)
.build()
)
.withRequestedId(CLUSTER_1_ID)
.withResources(new ExecutionEnvironment(configs, null, null))
.build();
Mockito
.when(this.jpaFileRepository.findByFile(Mockito.anyString()))
.thenReturn(Optional.of(new FileEntity(UUID.randomUUID().toString())));
Mockito
.when(this.jpaClusterRepository.save(Mockito.any(ClusterEntity.class)))
.thenThrow(new DuplicateKeyException("Duplicate Key"));
Assertions
.assertThatExceptionOfType(IdAlreadyExistsException.class)
.isThrownBy(() -> this.service.saveCluster(request));
}
@Test
void testUpdateClusterNoClusterExists() {
final String id = UUID.randomUUID().toString();
Mockito.when(this.jpaClusterRepository.findByUniqueId(id)).thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(
() -> this.service.updateCluster(
id,
new Cluster(
id,
Instant.now(),
Instant.now(),
new ExecutionEnvironment(null, null, null),
new ClusterMetadata.Builder(" ", " ", " ", ClusterStatus.UP).build()
)
)
);
}
@Test
void testUpdateClusterIdsDontMatch() {
final String id = UUID.randomUUID().toString();
final Cluster cluster = Mockito.mock(Cluster.class);
Mockito.when(this.jpaClusterRepository.existsByUniqueId(id)).thenReturn(true);
Mockito.when(cluster.getId()).thenReturn(UUID.randomUUID().toString());
Assertions
.assertThatExceptionOfType(PreconditionFailedException.class)
.isThrownBy(() -> this.service.updateCluster(id, cluster));
}
@Test
void testAddConfigsToClusterNoCluster() {
final String id = UUID.randomUUID().toString();
Mockito.when(this.jpaClusterRepository.findByUniqueId(id)).thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.service.addConfigsToResource(id, Sets.newHashSet(), Cluster.class));
}
@Test
void testUpdateConfigsForClusterNoCluster() {
final String id = UUID.randomUUID().toString();
Mockito.when(this.jpaClusterRepository.findByUniqueId(id)).thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.service.updateConfigsForResource(id, Sets.newHashSet(), Cluster.class));
}
@Test
void testGetConfigsForClusterNoCluster() {
final String id = UUID.randomUUID().toString();
Mockito.when(this.jpaClusterRepository.findByUniqueId(id)).thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.service.getConfigsForResource(id, Cluster.class));
}
@Test
void testAddDepsToClusterNoCluster() {
final String id = UUID.randomUUID().toString();
Mockito.when(this.jpaClusterRepository.findByUniqueId(id)).thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.service.addDependenciesToResource(id, Sets.newHashSet(), Cluster.class));
}
@Test
void testUpdateDepsForClusterNoCluster() {
final String id = UUID.randomUUID().toString();
Mockito.when(this.jpaClusterRepository.findByUniqueId(id)).thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.service.updateDependenciesForResource(id, Sets.newHashSet(), Cluster.class));
}
@Test
void testGetDepsForClusterNoCluster() {
final String id = UUID.randomUUID().toString();
Mockito.when(this.jpaClusterRepository.findByUniqueId(id)).thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.service.getDependenciesForResource(id, Cluster.class));
}
@Test
void testRemoveAllDepsFromClusterNoCluster() {
final String id = UUID.randomUUID().toString();
Mockito.when(this.jpaClusterRepository.findByUniqueId(id)).thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.service.removeAllDependenciesForResource(id, Cluster.class));
}
@Test
void testRemoveDepFromClusterNoCluster() {
final String id = UUID.randomUUID().toString();
Mockito.when(this.jpaClusterRepository.findByUniqueId(id)).thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.service.removeDependencyForResource(id, "something", Cluster.class));
}
@Test
void testAddTagsForClusterNoCluster() {
final String id = UUID.randomUUID().toString();
Mockito.when(this.jpaClusterRepository.findByUniqueId(id)).thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.service.addTagsToResource(id, Sets.newHashSet(), Cluster.class));
}
@Test
void testUpdateTagsForClusterNoCluster() {
final String id = UUID.randomUUID().toString();
Mockito.when(this.jpaClusterRepository.findByUniqueId(id)).thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.service.updateTagsForResource(id, Sets.newHashSet(), Cluster.class));
}
@Test
void testGetTagsForClusterNoCluster() {
final String id = UUID.randomUUID().toString();
Mockito.when(this.jpaClusterRepository.findByUniqueId(id)).thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.service.getTagsForResource(id, Cluster.class));
}
@Test
void testRemoveAllTagsForClusterNoCluster() {
final String id = UUID.randomUUID().toString();
Mockito.when(this.jpaClusterRepository.findByUniqueId(id)).thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.service.removeAllTagsForResource(id, Cluster.class));
}
@Test
void testRemoveTagForClusterNoCluster() {
final String id = UUID.randomUUID().toString();
Mockito.when(this.jpaClusterRepository.findByUniqueId(id)).thenReturn(Optional.empty());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.service.removeTagForResource(id, "something", Cluster.class));
}
}
| 2,412 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/data/services/impl
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/data/services/impl/jpa/package-info.java
|
/*
*
* Copyright 2020 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Tests for this package.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.data.services.impl.jpa;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,413 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/data/services/impl/jpa/queries
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/data/services/impl/jpa/queries/predicates/ClusterPredicatesTest.java
|
/*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.genie.web.data.services.impl.jpa.queries.predicates;
import com.google.common.collect.Sets;
import com.netflix.genie.common.internal.dtos.ClusterStatus;
import com.netflix.genie.web.data.services.impl.jpa.entities.ClusterEntity;
import com.netflix.genie.web.data.services.impl.jpa.entities.ClusterEntity_;
import com.netflix.genie.web.data.services.impl.jpa.entities.TagEntity;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.persistence.criteria.SetJoin;
import java.time.Instant;
import java.util.Set;
/**
* Tests for {@link ClusterPredicates}.
*
* @author tgianos
*/
class ClusterPredicatesTest {
private static final String NAME = "h2prod";
private static final TagEntity TAG_1 = new TagEntity("prod");
private static final TagEntity TAG_2 = new TagEntity("yarn");
private static final TagEntity TAG_3 = new TagEntity("hadoop");
private static final ClusterStatus STATUS_1 = ClusterStatus.UP;
private static final ClusterStatus STATUS_2 = ClusterStatus.OUT_OF_SERVICE;
private static final Set<TagEntity> TAGS = Sets.newHashSet(TAG_1, TAG_2, TAG_3);
private static final Set<String> STATUSES = Sets.newHashSet(
STATUS_1.name(),
STATUS_2.name()
);
private static final Instant MIN_UPDATE_TIME = Instant.ofEpochMilli(123467L);
private static final Instant MAX_UPDATE_TIME = Instant.ofEpochMilli(1234643L);
private Root<ClusterEntity> root;
private CriteriaQuery<?> cq;
private CriteriaBuilder cb;
private SetJoin<ClusterEntity, TagEntity> tagEntityJoin;
@BeforeEach
@SuppressWarnings("unchecked")
void setup() {
this.root = (Root<ClusterEntity>) Mockito.mock(Root.class);
this.cq = Mockito.mock(CriteriaQuery.class);
this.cb = Mockito.mock(CriteriaBuilder.class);
final Path<Long> idPath = (Path<Long>) Mockito.mock(Path.class);
Mockito.when(this.root.get(ClusterEntity_.id)).thenReturn(idPath);
final Path<String> clusterNamePath = (Path<String>) Mockito.mock(Path.class);
final Predicate likeNamePredicate = Mockito.mock(Predicate.class);
final Predicate equalNamePredicate = Mockito.mock(Predicate.class);
Mockito.when(this.root.get(ClusterEntity_.name)).thenReturn(clusterNamePath);
Mockito.when(this.cb.like(clusterNamePath, NAME)).thenReturn(likeNamePredicate);
Mockito.when(this.cb.equal(clusterNamePath, NAME)).thenReturn(equalNamePredicate);
final Path<Instant> minUpdatePath = (Path<Instant>) Mockito.mock(Path.class);
final Predicate greaterThanOrEqualToPredicate = Mockito.mock(Predicate.class);
Mockito.when(this.root.get(ClusterEntity_.updated)).thenReturn(minUpdatePath);
Mockito.when(this.cb.greaterThanOrEqualTo(minUpdatePath, MIN_UPDATE_TIME))
.thenReturn(greaterThanOrEqualToPredicate);
final Path<Instant> maxUpdatePath = (Path<Instant>) Mockito.mock(Path.class);
final Predicate lessThanPredicate = Mockito.mock(Predicate.class);
Mockito.when(this.root.get(ClusterEntity_.updated)).thenReturn(maxUpdatePath);
Mockito.when(this.cb.lessThan(maxUpdatePath, MAX_UPDATE_TIME)).thenReturn(lessThanPredicate);
final Path<String> statusPath = (Path<String>) Mockito.mock(Path.class);
final Predicate equalStatusPredicate = Mockito.mock(Predicate.class);
Mockito.when(this.root.get(ClusterEntity_.status)).thenReturn(statusPath);
Mockito
.when(this.cb.equal(Mockito.eq(statusPath), Mockito.anyString()))
.thenReturn(equalStatusPredicate);
this.tagEntityJoin = (SetJoin<ClusterEntity, TagEntity>) Mockito.mock(SetJoin.class);
Mockito.when(this.root.join(ClusterEntity_.tags)).thenReturn(this.tagEntityJoin);
final Predicate tagInPredicate = Mockito.mock(Predicate.class);
Mockito.when(this.tagEntityJoin.in(TAGS)).thenReturn(tagInPredicate);
final Expression<Long> idCountExpression = (Expression<Long>) Mockito.mock(Expression.class);
Mockito.when(this.cb.count(Mockito.any())).thenReturn(idCountExpression);
final Predicate havingPredicate = Mockito.mock(Predicate.class);
Mockito.when(this.cb.equal(idCountExpression, TAGS.size())).thenReturn(havingPredicate);
}
@Test
void testFindAll() {
ClusterPredicates
.find(
this.root,
this.cq,
this.cb,
NAME,
STATUSES,
TAGS,
MIN_UPDATE_TIME,
MAX_UPDATE_TIME
);
Mockito.verify(this.cb, Mockito.times(1))
.equal(this.root.get(ClusterEntity_.name), NAME);
Mockito.verify(this.cb, Mockito.times(1))
.greaterThanOrEqualTo(this.root.get(ClusterEntity_.updated), MIN_UPDATE_TIME);
Mockito.verify(this.cb, Mockito.times(1)).lessThan(this.root.get(ClusterEntity_.updated), MAX_UPDATE_TIME);
Mockito.verify(this.root, Mockito.times(1)).join(ClusterEntity_.tags);
Mockito.verify(this.tagEntityJoin, Mockito.times(1)).in(TAGS);
Mockito.verify(this.cq, Mockito.times(1)).groupBy(Mockito.any(Path.class));
Mockito.verify(this.cq, Mockito.times(1)).having(Mockito.any(Predicate.class));
for (final String status : STATUSES) {
Mockito.verify(this.cb, Mockito.times(1))
.equal(this.root.get(ClusterEntity_.status), status);
}
}
@Test
void testFindAllLike() {
final String newName = NAME + "%";
ClusterPredicates
.find(
this.root,
this.cq,
this.cb,
newName,
STATUSES,
TAGS,
MIN_UPDATE_TIME,
MAX_UPDATE_TIME
);
Mockito.verify(this.cb, Mockito.times(1))
.like(this.root.get(ClusterEntity_.name), newName);
Mockito.verify(this.cb, Mockito.times(1))
.greaterThanOrEqualTo(this.root.get(ClusterEntity_.updated), MIN_UPDATE_TIME);
Mockito.verify(this.cb, Mockito.times(1)).lessThan(this.root.get(ClusterEntity_.updated), MAX_UPDATE_TIME);
Mockito.verify(this.root, Mockito.times(1)).join(ClusterEntity_.tags);
Mockito.verify(this.tagEntityJoin, Mockito.times(1)).in(TAGS);
Mockito.verify(this.cq, Mockito.times(1)).groupBy(Mockito.any(Path.class));
Mockito.verify(this.cq, Mockito.times(1)).having(Mockito.any(Predicate.class));
for (final String status : STATUSES) {
Mockito.verify(this.cb, Mockito.times(1))
.equal(this.root.get(ClusterEntity_.status), status);
}
}
@Test
void testFindNoName() {
ClusterPredicates
.find(
this.root,
this.cq,
this.cb,
null,
STATUSES,
TAGS,
MIN_UPDATE_TIME,
MAX_UPDATE_TIME
);
Mockito.verify(this.cb, Mockito.never())
.like(this.root.get(ClusterEntity_.name), NAME);
Mockito.verify(this.cb, Mockito.never())
.equal(this.root.get(ClusterEntity_.name), NAME);
Mockito.verify(this.cb, Mockito.times(1))
.greaterThanOrEqualTo(this.root.get(ClusterEntity_.updated), MIN_UPDATE_TIME);
Mockito.verify(this.cb, Mockito.times(1)).lessThan(this.root.get(ClusterEntity_.updated), MAX_UPDATE_TIME);
Mockito.verify(this.root, Mockito.times(1)).join(ClusterEntity_.tags);
Mockito.verify(this.tagEntityJoin, Mockito.times(1)).in(TAGS);
Mockito.verify(this.cq, Mockito.times(1)).groupBy(Mockito.any(Path.class));
Mockito.verify(this.cq, Mockito.times(1)).having(Mockito.any(Predicate.class));
for (final String status : STATUSES) {
Mockito.verify(this.cb, Mockito.times(1))
.equal(this.root.get(ClusterEntity_.status), status);
}
}
@Test
void testFindNoStatuses() {
ClusterPredicates
.find(
this.root,
this.cq,
this.cb,
NAME,
null,
TAGS,
MIN_UPDATE_TIME,
MAX_UPDATE_TIME
);
Mockito.verify(this.cb, Mockito.times(1))
.equal(this.root.get(ClusterEntity_.name), NAME);
Mockito.verify(this.cb, Mockito.times(1))
.greaterThanOrEqualTo(this.root.get(ClusterEntity_.updated), MIN_UPDATE_TIME);
Mockito.verify(this.cb, Mockito.times(1)).lessThan(
this.root.get(ClusterEntity_.updated), MAX_UPDATE_TIME);
Mockito.verify(this.root, Mockito.times(1)).join(ClusterEntity_.tags);
Mockito.verify(this.tagEntityJoin, Mockito.times(1)).in(TAGS);
Mockito.verify(this.cq, Mockito.times(1)).groupBy(Mockito.any(Path.class));
Mockito.verify(this.cq, Mockito.times(1)).having(Mockito.any(Predicate.class));
for (final String status : STATUSES) {
Mockito.verify(this.cb, Mockito.never())
.equal(this.root.get(ClusterEntity_.status), status);
}
}
@Test
void testFindEmptyStatuses() {
ClusterPredicates
.find(
this.root,
this.cq,
this.cb,
NAME,
Sets.newHashSet(),
TAGS,
MIN_UPDATE_TIME,
MAX_UPDATE_TIME
);
Mockito.verify(this.cb, Mockito.times(1))
.equal(this.root.get(ClusterEntity_.name), NAME);
Mockito.verify(this.cb, Mockito.times(1))
.greaterThanOrEqualTo(this.root.get(ClusterEntity_.updated), MIN_UPDATE_TIME);
Mockito.verify(this.cb, Mockito.times(1))
.lessThan(this.root.get(ClusterEntity_.updated), MAX_UPDATE_TIME);
Mockito.verify(this.root, Mockito.times(1)).join(ClusterEntity_.tags);
Mockito.verify(this.tagEntityJoin, Mockito.times(1)).in(TAGS);
Mockito.verify(this.cq, Mockito.times(1)).groupBy(Mockito.any(Path.class));
Mockito.verify(this.cq, Mockito.times(1)).having(Mockito.any(Predicate.class));
for (final String status : STATUSES) {
Mockito.verify(this.cb, Mockito.never())
.equal(this.root.get(ClusterEntity_.status), status);
}
}
@Test
void testFindNoTags() {
ClusterPredicates
.find(
this.root,
this.cq,
this.cb,
NAME,
STATUSES,
null,
MIN_UPDATE_TIME,
MAX_UPDATE_TIME
);
Mockito.verify(this.cb, Mockito.times(1))
.equal(this.root.get(ClusterEntity_.name), NAME);
Mockito.verify(this.cb, Mockito.times(1))
.greaterThanOrEqualTo(this.root.get(ClusterEntity_.updated), MIN_UPDATE_TIME);
Mockito.verify(this.cb, Mockito.times(1))
.lessThan(this.root.get(ClusterEntity_.updated), MAX_UPDATE_TIME);
Mockito.verify(this.root, Mockito.never()).join(ClusterEntity_.tags);
for (final String status : STATUSES) {
Mockito.verify(this.cb, Mockito.times(1))
.equal(this.root.get(ClusterEntity_.status), status);
}
}
@Test
void testFindNoMinTime() {
ClusterPredicates
.find(
this.root,
this.cq,
this.cb,
NAME,
STATUSES,
TAGS,
null,
MAX_UPDATE_TIME
);
Mockito.verify(this.cb, Mockito.times(1))
.equal(this.root.get(ClusterEntity_.name), NAME);
Mockito.verify(this.cb, Mockito.never())
.greaterThanOrEqualTo(this.root.get(ClusterEntity_.updated), MIN_UPDATE_TIME);
Mockito.verify(this.cb, Mockito.times(1))
.lessThan(this.root.get(ClusterEntity_.updated), MAX_UPDATE_TIME);
Mockito.verify(this.root, Mockito.times(1)).join(ClusterEntity_.tags);
Mockito.verify(this.tagEntityJoin, Mockito.times(1)).in(TAGS);
Mockito.verify(this.cq, Mockito.times(1)).groupBy(Mockito.any(Path.class));
Mockito.verify(this.cq, Mockito.times(1)).having(Mockito.any(Predicate.class));
for (final String status : STATUSES) {
Mockito.verify(this.cb, Mockito.times(1))
.equal(this.root.get(ClusterEntity_.status), status);
}
}
@Test
void testFindNoMax() {
ClusterPredicates
.find(
this.root,
this.cq,
this.cb,
NAME,
STATUSES,
TAGS,
MIN_UPDATE_TIME,
null
);
Mockito.verify(this.cb, Mockito.times(1))
.equal(this.root.get(ClusterEntity_.name), NAME);
Mockito.verify(this.cb, Mockito.times(1))
.greaterThanOrEqualTo(this.root.get(ClusterEntity_.updated), MIN_UPDATE_TIME);
Mockito.verify(this.cb, Mockito.never())
.lessThan(this.root.get(ClusterEntity_.updated), MAX_UPDATE_TIME);
Mockito.verify(this.root, Mockito.times(1)).join(ClusterEntity_.tags);
Mockito.verify(this.tagEntityJoin, Mockito.times(1)).in(TAGS);
Mockito.verify(this.cq, Mockito.times(1)).groupBy(Mockito.any(Path.class));
Mockito.verify(this.cq, Mockito.times(1)).having(Mockito.any(Predicate.class));
for (final String status : STATUSES) {
Mockito.verify(this.cb, Mockito.times(1))
.equal(this.root.get(ClusterEntity_.status), status);
}
}
}
| 2,414 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/data/services/impl/jpa/queries
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/data/services/impl/jpa/queries/predicates/PredicateUtilsTest.java
|
/*
*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.data.services.impl.jpa.queries.predicates;
import com.google.common.collect.Sets;
import com.netflix.genie.web.data.services.impl.jpa.entities.TagEntity;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import java.util.Set;
/**
* Unit tests for JpaSpecificationUtils.
*
* @author tgianos
* @since 3.0.0
*/
class PredicateUtilsTest {
/**
* Make sure the method to create the tag search string for jobs is working as expected.
*/
@Test
void canCreateTagSearchString() {
final String one = "oNe";
final String two = "TwO";
final String three = "3";
final Set<TagEntity> tags = Sets.newHashSet();
Assertions
.assertThat(PredicateUtils.createTagSearchString(tags))
.isEqualTo(
// Coerce to string... sigh
PredicateUtils.TAG_DELIMITER + PredicateUtils.TAG_DELIMITER
);
final TagEntity oneTag = new TagEntity();
oneTag.setTag(one);
final TagEntity twoTag = new TagEntity();
twoTag.setTag(two);
final TagEntity threeTag = new TagEntity();
threeTag.setTag(three);
tags.add(oneTag);
Assertions
.assertThat(PredicateUtils.createTagSearchString(tags))
.isEqualTo(
PredicateUtils.TAG_DELIMITER
+ one
+ PredicateUtils.TAG_DELIMITER
);
tags.add(twoTag);
Assertions.assertThat(PredicateUtils.createTagSearchString(tags))
.isEqualTo(
PredicateUtils.TAG_DELIMITER
+ one
+ PredicateUtils.TAG_DELIMITER
+ PredicateUtils.TAG_DELIMITER
+ two
+ PredicateUtils.TAG_DELIMITER
);
tags.add(threeTag);
Assertions.assertThat(PredicateUtils.createTagSearchString(tags))
.isEqualTo(
PredicateUtils.TAG_DELIMITER
+ three
+ PredicateUtils.TAG_DELIMITER
+ PredicateUtils.TAG_DELIMITER
+ one
+ PredicateUtils.TAG_DELIMITER
+ PredicateUtils.TAG_DELIMITER
+ two
+ PredicateUtils.TAG_DELIMITER
);
}
/**
* Make sure if a string parameter contains a % it returns a like predicate but if not it returns an equals
* predicate.
*/
@SuppressWarnings("unchecked")
@Test
void canGetStringLikeOrEqualPredicate() {
final CriteriaBuilder cb = Mockito.mock(CriteriaBuilder.class);
final Expression<String> expression = (Expression<String>) Mockito.mock(Expression.class);
final Predicate likePredicate = Mockito.mock(Predicate.class);
final Predicate equalPredicate = Mockito.mock(Predicate.class);
Mockito.when(cb.like(Mockito.eq(expression), Mockito.anyString())).thenReturn(likePredicate);
Mockito.when(cb.equal(Mockito.eq(expression), Mockito.anyString())).thenReturn(equalPredicate);
Assertions
.assertThat(PredicateUtils.getStringLikeOrEqualPredicate(cb, expression, "equal"))
.isEqualTo(equalPredicate);
Assertions
.assertThat(PredicateUtils.getStringLikeOrEqualPredicate(cb, expression, "lik%e"))
.isEqualTo(likePredicate);
}
/**
* Make sure we can get a valid like string for the tag list.
*/
@Test
void canGetTagLikeString() {
Assertions
.assertThat(PredicateUtils.getTagLikeString(Sets.newHashSet()))
.isEqualTo(
// coerce to String
PredicateUtils.PERCENT
);
Assertions
.assertThat(PredicateUtils.getTagLikeString(Sets.newHashSet("tag")))
.isEqualTo(
PredicateUtils.PERCENT
+ PredicateUtils.TAG_DELIMITER
+ "tag"
+ PredicateUtils.TAG_DELIMITER
+ PredicateUtils.PERCENT
);
Assertions
.assertThat(PredicateUtils.getTagLikeString(Sets.newHashSet("tag", "Stag", "rag")))
.isEqualTo(
PredicateUtils.PERCENT
+ PredicateUtils.TAG_DELIMITER
+ "rag"
+ PredicateUtils.TAG_DELIMITER
+ "%"
+ PredicateUtils.TAG_DELIMITER
+ "Stag"
+ PredicateUtils.TAG_DELIMITER
+ "%"
+ PredicateUtils.TAG_DELIMITER
+ "tag"
+ PredicateUtils.TAG_DELIMITER
+ PredicateUtils.PERCENT
);
}
}
| 2,415 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/data/services/impl/jpa/queries
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/data/services/impl/jpa/queries/predicates/JobPredicatesTest.java
|
/*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.genie.web.data.services.impl.jpa.queries.predicates;
import com.google.common.collect.Sets;
import com.netflix.genie.common.dto.JobStatus;
import com.netflix.genie.web.data.services.impl.jpa.entities.ClusterEntity;
import com.netflix.genie.web.data.services.impl.jpa.entities.CommandEntity;
import com.netflix.genie.web.data.services.impl.jpa.entities.JobEntity;
import com.netflix.genie.web.data.services.impl.jpa.entities.JobEntity_;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Set;
import java.util.UUID;
/**
* Tests for {@link JobPredicates}.
*
* @author tgianos
*/
class JobPredicatesTest {
private static final String ID = UUID.randomUUID().toString();
private static final String JOB_NAME = "jobName";
private static final String USER_NAME = "tgianos";
private static final String CLUSTER_NAME = "hprod2";
private static final ClusterEntity CLUSTER = Mockito.mock(ClusterEntity.class);
private static final String COMMAND_NAME = "pig";
private static final CommandEntity COMMAND = Mockito.mock(CommandEntity.class);
private static final Set<String> TAGS = Sets.newHashSet();
private static final Set<String> STATUSES = Sets.newHashSet();
private static final String TAG = UUID.randomUUID().toString();
private static final Instant MIN_STARTED = Instant.now();
private static final Instant MAX_STARTED = MIN_STARTED.plus(10, ChronoUnit.MILLIS);
private static final Instant MIN_FINISHED = MAX_STARTED.plus(10, ChronoUnit.MILLIS);
private static final Instant MAX_FINISHED = MIN_FINISHED.plus(10, ChronoUnit.MILLIS);
private static final String GROUPING = UUID.randomUUID().toString();
private static final String GROUPING_INSTANCE = UUID.randomUUID().toString();
private Root<JobEntity> root;
private CriteriaBuilder cb;
private String tagLikeStatement;
@BeforeEach
@SuppressWarnings("unchecked")
void setup() {
TAGS.clear();
TAGS.add(TAG);
STATUSES.clear();
STATUSES.add(JobStatus.INIT.name());
STATUSES.add(JobStatus.FAILED.name());
this.root = (Root<JobEntity>) Mockito.mock(Root.class);
this.cb = Mockito.mock(CriteriaBuilder.class);
final Path<String> idPath = (Path<String>) Mockito.mock(Path.class);
final Predicate likeIdPredicate = Mockito.mock(Predicate.class);
final Predicate equalIdPredicate = Mockito.mock(Predicate.class);
Mockito.when(this.root.get(JobEntity_.uniqueId)).thenReturn(idPath);
Mockito.when(this.cb.like(idPath, ID)).thenReturn(likeIdPredicate);
Mockito.when(this.cb.equal(idPath, ID)).thenReturn(equalIdPredicate);
final Path<String> jobNamePath = (Path<String>) Mockito.mock(Path.class);
final Predicate likeJobNamePredicate = Mockito.mock(Predicate.class);
final Predicate equalJobNamePredicate = Mockito.mock(Predicate.class);
Mockito.when(this.root.get(JobEntity_.name)).thenReturn(jobNamePath);
Mockito.when(this.cb.like(jobNamePath, JOB_NAME)).thenReturn(likeJobNamePredicate);
Mockito.when(this.cb.equal(jobNamePath, JOB_NAME)).thenReturn(equalJobNamePredicate);
final Path<String> userNamePath = (Path<String>) Mockito.mock(Path.class);
final Predicate equalUserNamePredicate = Mockito.mock(Predicate.class);
Mockito.when(this.root.get(JobEntity_.user)).thenReturn(userNamePath);
Mockito.when(this.cb.equal(userNamePath, USER_NAME)).thenReturn(equalUserNamePredicate);
final Path<String> statusPath = (Path<String>) Mockito.mock(Path.class);
final Predicate equalStatusPredicate = Mockito.mock(Predicate.class);
Mockito.when(this.root.get(JobEntity_.status)).thenReturn(statusPath);
Mockito
.when(this.cb.equal(Mockito.eq(statusPath), Mockito.any(JobStatus.class)))
.thenReturn(equalStatusPredicate);
final Path<String> clusterNamePath = (Path<String>) Mockito.mock(Path.class);
final Predicate equalClusterNamePredicate = Mockito.mock(Predicate.class);
Mockito.when(this.root.get(JobEntity_.clusterName)).thenReturn(clusterNamePath);
Mockito.when(this.cb.equal(clusterNamePath, CLUSTER_NAME)).thenReturn(equalClusterNamePredicate);
final Path<ClusterEntity> clusterIdPath = (Path<ClusterEntity>) Mockito.mock(Path.class);
final Predicate equalClusterIdPredicate = Mockito.mock(Predicate.class);
Mockito.when(this.root.get(JobEntity_.cluster)).thenReturn(clusterIdPath);
Mockito.when(this.cb.equal(clusterIdPath, CLUSTER)).thenReturn(equalClusterIdPredicate);
final Path<String> commandNamePath = (Path<String>) Mockito.mock(Path.class);
final Predicate equalCommandNamePredicate = Mockito.mock(Predicate.class);
Mockito.when(this.root.get(JobEntity_.commandName)).thenReturn(commandNamePath);
Mockito.when(this.cb.equal(commandNamePath, COMMAND_NAME)).thenReturn(equalCommandNamePredicate);
final Path<CommandEntity> commandIdPath = (Path<CommandEntity>) Mockito.mock(Path.class);
final Predicate equalCommandIdPredicate = Mockito.mock(Predicate.class);
Mockito.when(this.root.get(JobEntity_.command)).thenReturn(commandIdPath);
Mockito.when(this.cb.equal(clusterIdPath, COMMAND)).thenReturn(equalCommandIdPredicate);
final Path<String> tagPath = (Path<String>) Mockito.mock(Path.class);
final Predicate likeTagPredicate = Mockito.mock(Predicate.class);
Mockito.when(this.root.get(JobEntity_.tagSearchString)).thenReturn(tagPath);
Mockito.when(this.cb.like(Mockito.eq(tagPath), Mockito.any(String.class))).thenReturn(likeTagPredicate);
this.tagLikeStatement = PredicateUtils.getTagLikeString(TAGS);
final Path<Instant> startedPath = (Path<Instant>) Mockito.mock(Path.class);
final Predicate minStartedPredicate = Mockito.mock(Predicate.class);
Mockito.when(this.root.get(JobEntity_.started)).thenReturn(startedPath);
Mockito
.when(this.cb.greaterThanOrEqualTo(Mockito.eq(startedPath), Mockito.eq(MIN_STARTED)))
.thenReturn(minStartedPredicate);
final Predicate maxStartedPredicate = Mockito.mock(Predicate.class);
Mockito
.when(this.cb.lessThan(Mockito.eq(startedPath), Mockito.eq(MAX_STARTED)))
.thenReturn(maxStartedPredicate);
final Path<Instant> finishedPath = (Path<Instant>) Mockito.mock(Path.class);
final Predicate minFinishedPredicate = Mockito.mock(Predicate.class);
Mockito.when(this.root.get(JobEntity_.finished)).thenReturn(finishedPath);
Mockito
.when(this.cb.greaterThanOrEqualTo(Mockito.eq(finishedPath), Mockito.eq(MIN_FINISHED)))
.thenReturn(minFinishedPredicate);
final Predicate maxFinishedPredicate = Mockito.mock(Predicate.class);
Mockito
.when(this.cb.lessThan(Mockito.eq(finishedPath), Mockito.eq(MAX_FINISHED)))
.thenReturn(maxFinishedPredicate);
final Path<String> groupingPath = (Path<String>) Mockito.mock(Path.class);
final Predicate equalGroupingPredicate = Mockito.mock(Predicate.class);
Mockito.when(this.root.get(JobEntity_.grouping)).thenReturn(groupingPath);
Mockito.when(this.cb.equal(groupingPath, GROUPING)).thenReturn(equalGroupingPredicate);
final Path<String> groupingInstancePath = (Path<String>) Mockito.mock(Path.class);
final Predicate equalGroupingInstancePredicate = Mockito.mock(Predicate.class);
Mockito.when(this.root.get(JobEntity_.groupingInstance)).thenReturn(groupingInstancePath);
Mockito.when(this.cb.equal(groupingInstancePath, GROUPING_INSTANCE)).thenReturn(equalGroupingInstancePredicate);
}
@Test
void testFindWithAll() {
JobPredicates.getFindPredicate(
this.root,
this.cb,
ID,
JOB_NAME,
USER_NAME,
STATUSES,
TAGS,
CLUSTER_NAME,
CLUSTER,
COMMAND_NAME,
COMMAND,
MIN_STARTED,
MAX_STARTED,
MIN_FINISHED,
MAX_FINISHED,
GROUPING,
GROUPING_INSTANCE
);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.uniqueId), ID);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.name), JOB_NAME);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.user), USER_NAME);
for (final String status : STATUSES) {
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.status), status);
}
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.clusterName), CLUSTER_NAME);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.cluster), CLUSTER);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.commandName), COMMAND_NAME);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.command), COMMAND);
Mockito.
verify(this.cb, Mockito.times(1))
.like(this.root.get(JobEntity_.tagSearchString), this.tagLikeStatement);
Mockito.verify(this.cb, Mockito.times(1)).greaterThanOrEqualTo(this.root.get(JobEntity_.started), MIN_STARTED);
Mockito.verify(this.cb, Mockito.times(1)).lessThan(this.root.get(JobEntity_.started), MAX_STARTED);
Mockito
.verify(this.cb, Mockito.times(1))
.greaterThanOrEqualTo(this.root.get(JobEntity_.finished), MIN_FINISHED);
Mockito.verify(this.cb, Mockito.times(1)).lessThan(this.root.get(JobEntity_.finished), MAX_FINISHED);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.grouping), GROUPING);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.groupingInstance), GROUPING_INSTANCE);
}
@Test
void testFindWithAllLikes() {
final String newId = ID + "%";
final String newName = JOB_NAME + "%";
final String newUserName = USER_NAME + "%";
final String newClusterName = CLUSTER_NAME + "%";
final String newCommandName = COMMAND_NAME + "%";
final String newGrouping = GROUPING + "%";
final String newGroupingInstance = GROUPING_INSTANCE + "%";
JobPredicates.getFindPredicate(
this.root,
this.cb,
newId,
newName,
newUserName,
STATUSES,
TAGS,
newClusterName,
CLUSTER,
newCommandName,
COMMAND,
MIN_STARTED,
MAX_STARTED,
MIN_FINISHED,
MAX_FINISHED,
newGrouping,
newGroupingInstance
);
Mockito.verify(this.cb, Mockito.times(1)).like(this.root.get(JobEntity_.uniqueId), newId);
Mockito.verify(this.cb, Mockito.times(1)).like(this.root.get(JobEntity_.name), newName);
Mockito.verify(this.cb, Mockito.times(1)).like(this.root.get(JobEntity_.user), newUserName);
for (final String status : STATUSES) {
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.status), status);
}
Mockito.verify(this.cb, Mockito.times(1)).like(this.root.get(JobEntity_.clusterName), newClusterName);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.cluster), CLUSTER);
Mockito.verify(this.cb, Mockito.times(1)).like(this.root.get(JobEntity_.commandName), newCommandName);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.command), COMMAND);
Mockito
.verify(this.cb, Mockito.times(1))
.like(this.root.get(JobEntity_.tagSearchString), this.tagLikeStatement);
Mockito.verify(this.cb, Mockito.times(1)).greaterThanOrEqualTo(this.root.get(JobEntity_.started), MIN_STARTED);
Mockito.verify(this.cb, Mockito.times(1)).lessThan(this.root.get(JobEntity_.started), MAX_STARTED);
Mockito
.verify(this.cb, Mockito.times(1))
.greaterThanOrEqualTo(this.root.get(JobEntity_.finished), MIN_FINISHED);
Mockito.verify(this.cb, Mockito.times(1)).lessThan(this.root.get(JobEntity_.finished), MAX_FINISHED);
Mockito.verify(this.cb, Mockito.times(1)).like(this.root.get(JobEntity_.grouping), newGrouping);
Mockito.verify(this.cb, Mockito.times(1)).like(this.root.get(JobEntity_.groupingInstance), newGroupingInstance);
}
@Test
void testFindWithOutId() {
JobPredicates.getFindPredicate(
this.root,
this.cb,
null,
JOB_NAME,
USER_NAME,
STATUSES,
TAGS,
CLUSTER_NAME,
CLUSTER,
COMMAND_NAME,
COMMAND,
MIN_STARTED,
MAX_STARTED,
MIN_FINISHED,
MAX_FINISHED,
GROUPING,
GROUPING_INSTANCE
);
Mockito.verify(this.cb, Mockito.never()).like(this.root.get(JobEntity_.uniqueId), ID);
Mockito.verify(this.cb, Mockito.never()).equal(this.root.get(JobEntity_.uniqueId), ID);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.name), JOB_NAME);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.user), USER_NAME);
for (final String status : STATUSES) {
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.status), status);
}
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.clusterName), CLUSTER_NAME);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.cluster), CLUSTER);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.commandName), COMMAND_NAME);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.command), COMMAND);
Mockito
.verify(this.cb, Mockito.times(1))
.like(this.root.get(JobEntity_.tagSearchString), this.tagLikeStatement);
Mockito.verify(this.cb, Mockito.times(1)).greaterThanOrEqualTo(this.root.get(JobEntity_.started), MIN_STARTED);
Mockito.verify(this.cb, Mockito.times(1)).lessThan(this.root.get(JobEntity_.started), MAX_STARTED);
Mockito
.verify(this.cb, Mockito.times(1))
.greaterThanOrEqualTo(this.root.get(JobEntity_.finished), MIN_FINISHED);
Mockito.verify(this.cb, Mockito.times(1)).lessThan(this.root.get(JobEntity_.finished), MAX_FINISHED);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.grouping), GROUPING);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.groupingInstance), GROUPING_INSTANCE);
}
@Test
void testFindWithOutJobName() {
JobPredicates.getFindPredicate(
this.root,
this.cb,
ID,
null,
USER_NAME,
STATUSES,
TAGS,
CLUSTER_NAME,
CLUSTER,
COMMAND_NAME,
COMMAND,
MIN_STARTED,
MAX_STARTED,
MIN_FINISHED,
MAX_FINISHED,
GROUPING,
GROUPING_INSTANCE
);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.uniqueId), ID);
Mockito.verify(this.cb, Mockito.never()).like(this.root.get(JobEntity_.name), JOB_NAME);
Mockito.verify(this.cb, Mockito.never()).equal(this.root.get(JobEntity_.name), JOB_NAME);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.user), USER_NAME);
for (final String status : STATUSES) {
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.status), status);
}
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.clusterName), CLUSTER_NAME);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.cluster), CLUSTER);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.commandName), COMMAND_NAME);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.command), COMMAND);
Mockito
.verify(this.cb, Mockito.times(1))
.like(this.root.get(JobEntity_.tagSearchString), this.tagLikeStatement);
Mockito.verify(this.cb, Mockito.times(1)).greaterThanOrEqualTo(this.root.get(JobEntity_.started), MIN_STARTED);
Mockito.verify(this.cb, Mockito.times(1)).lessThan(this.root.get(JobEntity_.started), MAX_STARTED);
Mockito
.verify(this.cb, Mockito.times(1))
.greaterThanOrEqualTo(this.root.get(JobEntity_.finished), MIN_FINISHED);
Mockito.verify(this.cb, Mockito.times(1)).lessThan(this.root.get(JobEntity_.finished), MAX_FINISHED);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.grouping), GROUPING);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.groupingInstance), GROUPING_INSTANCE);
}
@Test
void testFindWithOutUserName() {
JobPredicates.getFindPredicate(
this.root,
this.cb,
ID,
JOB_NAME,
null,
STATUSES,
TAGS,
CLUSTER_NAME,
CLUSTER,
COMMAND_NAME,
COMMAND,
MIN_STARTED,
MAX_STARTED,
MIN_FINISHED,
MAX_FINISHED,
GROUPING,
GROUPING_INSTANCE
);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.uniqueId), ID);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.name), JOB_NAME);
Mockito.verify(this.cb, Mockito.never()).equal(this.root.get(JobEntity_.user), USER_NAME);
Mockito.verify(this.cb, Mockito.never()).like(this.root.get(JobEntity_.user), USER_NAME);
for (final String status : STATUSES) {
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.status), status);
}
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.clusterName), CLUSTER_NAME);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.cluster), CLUSTER);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.commandName), COMMAND_NAME);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.command), COMMAND);
Mockito
.verify(this.cb, Mockito.times(1))
.like(this.root.get(JobEntity_.tagSearchString), this.tagLikeStatement);
Mockito.verify(this.cb, Mockito.times(1)).greaterThanOrEqualTo(this.root.get(JobEntity_.started), MIN_STARTED);
Mockito.verify(this.cb, Mockito.times(1)).lessThan(this.root.get(JobEntity_.started), MAX_STARTED);
Mockito
.verify(this.cb, Mockito.times(1))
.greaterThanOrEqualTo(this.root.get(JobEntity_.finished), MIN_FINISHED);
Mockito.verify(this.cb, Mockito.times(1)).lessThan(this.root.get(JobEntity_.finished), MAX_FINISHED);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.grouping), GROUPING);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.groupingInstance), GROUPING_INSTANCE);
}
@Test
void testFindWithOutStatus() {
JobPredicates.getFindPredicate(
this.root,
this.cb,
ID,
JOB_NAME,
USER_NAME,
null,
TAGS,
CLUSTER_NAME,
CLUSTER,
COMMAND_NAME,
COMMAND,
MIN_STARTED,
MAX_STARTED,
MIN_FINISHED,
MAX_FINISHED,
GROUPING,
GROUPING_INSTANCE
);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.uniqueId), ID);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.name), JOB_NAME);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.user), USER_NAME);
for (final String status : STATUSES) {
Mockito.verify(this.cb, Mockito.never()).equal(this.root.get(JobEntity_.status), status);
}
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.clusterName), CLUSTER_NAME);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.cluster), CLUSTER);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.commandName), COMMAND_NAME);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.command), COMMAND);
Mockito
.verify(this.cb, Mockito.times(1))
.like(this.root.get(JobEntity_.tagSearchString), this.tagLikeStatement);
Mockito.verify(this.cb, Mockito.times(1)).greaterThanOrEqualTo(this.root.get(JobEntity_.started), MIN_STARTED);
Mockito.verify(this.cb, Mockito.times(1)).lessThan(this.root.get(JobEntity_.started), MAX_STARTED);
Mockito
.verify(this.cb, Mockito.times(1))
.greaterThanOrEqualTo(this.root.get(JobEntity_.finished), MIN_FINISHED);
Mockito.verify(this.cb, Mockito.times(1)).lessThan(this.root.get(JobEntity_.finished), MAX_FINISHED);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.grouping), GROUPING);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.groupingInstance), GROUPING_INSTANCE);
}
@Test
void testFindWithEmptyStatus() {
JobPredicates.getFindPredicate(
this.root,
this.cb,
ID,
JOB_NAME,
USER_NAME,
Sets.newHashSet(),
TAGS,
CLUSTER_NAME,
CLUSTER,
COMMAND_NAME,
COMMAND,
MIN_STARTED,
MAX_STARTED,
MIN_FINISHED,
MAX_FINISHED,
GROUPING,
GROUPING_INSTANCE
);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.uniqueId), ID);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.name), JOB_NAME);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.user), USER_NAME);
for (final String status : STATUSES) {
Mockito.verify(this.cb, Mockito.never()).equal(this.root.get(JobEntity_.status), status);
}
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.clusterName), CLUSTER_NAME);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.cluster), CLUSTER);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.commandName), COMMAND_NAME);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.command), COMMAND);
Mockito
.verify(this.cb, Mockito.times(1))
.like(this.root.get(JobEntity_.tagSearchString), this.tagLikeStatement);
Mockito.verify(this.cb, Mockito.times(1)).greaterThanOrEqualTo(this.root.get(JobEntity_.started), MIN_STARTED);
Mockito.verify(this.cb, Mockito.times(1)).lessThan(this.root.get(JobEntity_.started), MAX_STARTED);
Mockito
.verify(this.cb, Mockito.times(1))
.greaterThanOrEqualTo(this.root.get(JobEntity_.finished), MIN_FINISHED);
Mockito.verify(this.cb, Mockito.times(1)).lessThan(this.root.get(JobEntity_.finished), MAX_FINISHED);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.grouping), GROUPING);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.groupingInstance), GROUPING_INSTANCE);
}
@Test
void testFindWithOutClusterName() {
JobPredicates.getFindPredicate(
this.root,
this.cb,
ID,
JOB_NAME,
USER_NAME,
STATUSES,
TAGS,
null,
CLUSTER,
COMMAND_NAME,
COMMAND,
MIN_STARTED,
MAX_STARTED,
MIN_FINISHED,
MAX_FINISHED,
GROUPING,
GROUPING_INSTANCE
);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.uniqueId), ID);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.name), JOB_NAME);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.user), USER_NAME);
for (final String status : STATUSES) {
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.status), status);
}
Mockito.verify(this.cb, Mockito.never()).equal(this.root.get(JobEntity_.clusterName), CLUSTER_NAME);
Mockito.verify(this.cb, Mockito.never()).like(this.root.get(JobEntity_.clusterName), CLUSTER_NAME);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.cluster), CLUSTER);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.commandName), COMMAND_NAME);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.command), COMMAND);
Mockito
.verify(this.cb, Mockito.times(1))
.like(this.root.get(JobEntity_.tagSearchString), this.tagLikeStatement);
Mockito.verify(this.cb, Mockito.times(1)).greaterThanOrEqualTo(this.root.get(JobEntity_.started), MIN_STARTED);
Mockito.verify(this.cb, Mockito.times(1)).lessThan(this.root.get(JobEntity_.started), MAX_STARTED);
Mockito
.verify(this.cb, Mockito.times(1))
.greaterThanOrEqualTo(this.root.get(JobEntity_.finished), MIN_FINISHED);
Mockito.verify(this.cb, Mockito.times(1)).lessThan(this.root.get(JobEntity_.finished), MAX_FINISHED);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.grouping), GROUPING);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.groupingInstance), GROUPING_INSTANCE);
}
@Test
void testFindWithOutClusterId() {
JobPredicates.getFindPredicate(
this.root,
this.cb,
ID,
JOB_NAME,
USER_NAME,
STATUSES,
TAGS,
CLUSTER_NAME,
null,
COMMAND_NAME,
COMMAND,
MIN_STARTED,
MAX_STARTED,
MIN_FINISHED,
MAX_FINISHED,
GROUPING,
GROUPING_INSTANCE
);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.uniqueId), ID);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.name), JOB_NAME);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.user), USER_NAME);
for (final String status : STATUSES) {
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.status), status);
}
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.clusterName), CLUSTER_NAME);
Mockito.verify(this.cb, Mockito.never()).equal(this.root.get(JobEntity_.cluster), CLUSTER);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.commandName), COMMAND_NAME);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.command), COMMAND);
Mockito
.verify(this.cb, Mockito.times(1))
.like(this.root.get(JobEntity_.tagSearchString), this.tagLikeStatement);
Mockito.verify(this.cb, Mockito.times(1)).greaterThanOrEqualTo(this.root.get(JobEntity_.started), MIN_STARTED);
Mockito.verify(this.cb, Mockito.times(1)).lessThan(this.root.get(JobEntity_.started), MAX_STARTED);
Mockito
.verify(this.cb, Mockito.times(1))
.greaterThanOrEqualTo(this.root.get(JobEntity_.finished), MIN_FINISHED);
Mockito.verify(this.cb, Mockito.times(1)).lessThan(this.root.get(JobEntity_.finished), MAX_FINISHED);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.grouping), GROUPING);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.groupingInstance), GROUPING_INSTANCE);
}
@Test
void testFindWithOutCommandName() {
JobPredicates.getFindPredicate(
this.root,
this.cb,
ID,
JOB_NAME,
USER_NAME,
STATUSES,
TAGS,
CLUSTER_NAME,
CLUSTER,
null,
COMMAND,
MIN_STARTED,
MAX_STARTED,
MIN_FINISHED,
MAX_FINISHED,
GROUPING,
GROUPING_INSTANCE
);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.uniqueId), ID);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.name), JOB_NAME);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.user), USER_NAME);
for (final String status : STATUSES) {
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.status), status);
}
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.clusterName), CLUSTER_NAME);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.cluster), CLUSTER);
Mockito.verify(this.cb, Mockito.never()).equal(this.root.get(JobEntity_.commandName), COMMAND_NAME);
Mockito.verify(this.cb, Mockito.never()).like(this.root.get(JobEntity_.commandName), COMMAND_NAME);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.command), COMMAND);
Mockito
.verify(this.cb, Mockito.times(1))
.like(this.root.get(JobEntity_.tagSearchString), this.tagLikeStatement);
Mockito.verify(this.cb, Mockito.times(1)).greaterThanOrEqualTo(this.root.get(JobEntity_.started), MIN_STARTED);
Mockito.verify(this.cb, Mockito.times(1)).lessThan(this.root.get(JobEntity_.started), MAX_STARTED);
Mockito
.verify(this.cb, Mockito.times(1))
.greaterThanOrEqualTo(this.root.get(JobEntity_.finished), MIN_FINISHED);
Mockito.verify(this.cb, Mockito.times(1)).lessThan(this.root.get(JobEntity_.finished), MAX_FINISHED);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.grouping), GROUPING);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.groupingInstance), GROUPING_INSTANCE);
}
@Test
void testFindWithOutCommandId() {
JobPredicates.getFindPredicate(
this.root,
this.cb,
ID,
JOB_NAME,
USER_NAME,
STATUSES,
TAGS,
CLUSTER_NAME,
CLUSTER,
COMMAND_NAME,
null,
MIN_STARTED,
MAX_STARTED,
MIN_FINISHED,
MAX_FINISHED,
GROUPING,
GROUPING_INSTANCE
);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.uniqueId), ID);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.name), JOB_NAME);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.user), USER_NAME);
for (final String status : STATUSES) {
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.status), status);
}
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.clusterName), CLUSTER_NAME);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.cluster), CLUSTER);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.commandName), COMMAND_NAME);
Mockito.verify(this.cb, Mockito.never()).equal(this.root.get(JobEntity_.command), COMMAND);
Mockito
.verify(this.cb, Mockito.times(1))
.like(this.root.get(JobEntity_.tagSearchString), this.tagLikeStatement);
Mockito.verify(this.cb, Mockito.times(1)).greaterThanOrEqualTo(this.root.get(JobEntity_.started), MIN_STARTED);
Mockito.verify(this.cb, Mockito.times(1)).lessThan(this.root.get(JobEntity_.started), MAX_STARTED);
Mockito
.verify(this.cb, Mockito.times(1))
.greaterThanOrEqualTo(this.root.get(JobEntity_.finished), MIN_FINISHED);
Mockito.verify(this.cb, Mockito.times(1)).lessThan(this.root.get(JobEntity_.finished), MAX_FINISHED);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.grouping), GROUPING);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.groupingInstance), GROUPING_INSTANCE);
}
@Test
void testFindWithOutTags() {
JobPredicates.getFindPredicate(
this.root,
this.cb,
ID,
JOB_NAME,
USER_NAME,
STATUSES,
null,
CLUSTER_NAME,
CLUSTER,
COMMAND_NAME,
COMMAND,
MIN_STARTED,
MAX_STARTED,
MIN_FINISHED,
MAX_FINISHED,
GROUPING,
GROUPING_INSTANCE
);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.uniqueId), ID);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.name), JOB_NAME);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.user), USER_NAME);
for (final String status : STATUSES) {
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.status), status);
}
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.clusterName), CLUSTER_NAME);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.cluster), CLUSTER);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.commandName), COMMAND_NAME);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.command), COMMAND);
Mockito.verify(this.cb, Mockito.never()).like(this.root.get(JobEntity_.tagSearchString), this.tagLikeStatement);
Mockito.verify(this.cb, Mockito.times(1)).greaterThanOrEqualTo(this.root.get(JobEntity_.started), MIN_STARTED);
Mockito.verify(this.cb, Mockito.times(1)).lessThan(this.root.get(JobEntity_.started), MAX_STARTED);
Mockito
.verify(this.cb, Mockito.times(1))
.greaterThanOrEqualTo(this.root.get(JobEntity_.finished), MIN_FINISHED);
Mockito.verify(this.cb, Mockito.times(1)).lessThan(this.root.get(JobEntity_.finished), MAX_FINISHED);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.grouping), GROUPING);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.groupingInstance), GROUPING_INSTANCE);
}
@Test
void testFindWithOutMinStarted() {
JobPredicates.getFindPredicate(
this.root,
this.cb,
ID,
JOB_NAME,
USER_NAME,
STATUSES,
TAGS,
CLUSTER_NAME,
CLUSTER,
COMMAND_NAME,
COMMAND,
null,
MAX_STARTED,
MIN_FINISHED,
MAX_FINISHED,
GROUPING,
GROUPING_INSTANCE
);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.uniqueId), ID);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.name), JOB_NAME);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.user), USER_NAME);
for (final String status : STATUSES) {
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.status), status);
}
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.clusterName), CLUSTER_NAME);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.cluster), CLUSTER);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.commandName), COMMAND_NAME);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.command), COMMAND);
Mockito
.verify(this.cb, Mockito.times(1))
.like(this.root.get(JobEntity_.tagSearchString), this.tagLikeStatement);
Mockito.verify(this.cb, Mockito.never()).greaterThanOrEqualTo(this.root.get(JobEntity_.started), MIN_STARTED);
Mockito.verify(this.cb, Mockito.times(1)).lessThan(this.root.get(JobEntity_.started), MAX_STARTED);
Mockito
.verify(this.cb, Mockito.times(1))
.greaterThanOrEqualTo(this.root.get(JobEntity_.finished), MIN_FINISHED);
Mockito.verify(this.cb, Mockito.times(1)).lessThan(this.root.get(JobEntity_.finished), MAX_FINISHED);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.grouping), GROUPING);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.groupingInstance), GROUPING_INSTANCE);
}
@Test
void testFindWithOutMaxStarted() {
JobPredicates.getFindPredicate(
this.root,
this.cb,
ID,
JOB_NAME,
USER_NAME,
STATUSES,
TAGS,
CLUSTER_NAME,
CLUSTER,
COMMAND_NAME,
COMMAND,
MIN_STARTED,
null,
MIN_FINISHED,
MAX_FINISHED,
GROUPING,
GROUPING_INSTANCE
);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.uniqueId), ID);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.name), JOB_NAME);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.user), USER_NAME);
for (final String status : STATUSES) {
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.status), status);
}
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.clusterName), CLUSTER_NAME);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.cluster), CLUSTER);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.commandName), COMMAND_NAME);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.command), COMMAND);
Mockito
.verify(this.cb, Mockito.times(1))
.like(this.root.get(JobEntity_.tagSearchString), this.tagLikeStatement);
Mockito.verify(this.cb, Mockito.times(1)).greaterThanOrEqualTo(this.root.get(JobEntity_.started), MIN_STARTED);
Mockito.verify(this.cb, Mockito.never()).lessThan(this.root.get(JobEntity_.started), MAX_STARTED);
Mockito
.verify(this.cb, Mockito.times(1))
.greaterThanOrEqualTo(this.root.get(JobEntity_.finished), MIN_FINISHED);
Mockito.verify(this.cb, Mockito.times(1)).lessThan(this.root.get(JobEntity_.finished), MAX_FINISHED);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.grouping), GROUPING);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.groupingInstance), GROUPING_INSTANCE);
}
@Test
void testFindWithOutMinFinished() {
JobPredicates.getFindPredicate(
this.root,
this.cb,
ID,
JOB_NAME,
USER_NAME,
STATUSES,
TAGS,
CLUSTER_NAME,
CLUSTER,
COMMAND_NAME,
COMMAND,
MIN_STARTED,
MAX_STARTED,
null,
MAX_FINISHED,
GROUPING,
GROUPING_INSTANCE
);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.uniqueId), ID);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.name), JOB_NAME);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.user), USER_NAME);
for (final String status : STATUSES) {
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.status), status);
}
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.clusterName), CLUSTER_NAME);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.cluster), CLUSTER);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.commandName), COMMAND_NAME);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.command), COMMAND);
Mockito
.verify(this.cb, Mockito.times(1))
.like(this.root.get(JobEntity_.tagSearchString), this.tagLikeStatement);
Mockito.verify(this.cb, Mockito.times(1)).greaterThanOrEqualTo(this.root.get(JobEntity_.started), MIN_STARTED);
Mockito.verify(this.cb, Mockito.times(1)).lessThan(this.root.get(JobEntity_.started), MAX_STARTED);
Mockito
.verify(this.cb, Mockito.never())
.greaterThanOrEqualTo(this.root.get(JobEntity_.finished), MIN_FINISHED);
Mockito.verify(this.cb, Mockito.times(1)).lessThan(this.root.get(JobEntity_.finished), MAX_FINISHED);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.grouping), GROUPING);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.groupingInstance), GROUPING_INSTANCE);
}
@Test
void testFindWithOutMaxFinished() {
JobPredicates.getFindPredicate(
this.root,
this.cb,
ID,
JOB_NAME,
USER_NAME,
STATUSES,
TAGS,
CLUSTER_NAME,
CLUSTER,
COMMAND_NAME,
COMMAND,
MIN_STARTED,
MAX_STARTED,
MIN_FINISHED,
null,
GROUPING,
GROUPING_INSTANCE
);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.uniqueId), ID);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.name), JOB_NAME);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.user), USER_NAME);
for (final String status : STATUSES) {
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.status), status);
}
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.clusterName), CLUSTER_NAME);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.cluster), CLUSTER);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.commandName), COMMAND_NAME);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.command), COMMAND);
Mockito
.verify(this.cb, Mockito.times(1))
.like(this.root.get(JobEntity_.tagSearchString), this.tagLikeStatement);
Mockito.verify(this.cb, Mockito.times(1)).greaterThanOrEqualTo(this.root.get(JobEntity_.started), MIN_STARTED);
Mockito.verify(this.cb, Mockito.times(1)).lessThan(this.root.get(JobEntity_.started), MAX_STARTED);
Mockito
.verify(this.cb, Mockito.times(1))
.greaterThanOrEqualTo(this.root.get(JobEntity_.finished), MIN_FINISHED);
Mockito.verify(this.cb, Mockito.never()).lessThan(this.root.get(JobEntity_.finished), MAX_FINISHED);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.grouping), GROUPING);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.groupingInstance), GROUPING_INSTANCE);
}
@Test
void testFindWithEmptyTag() {
TAGS.add("");
JobPredicates.getFindPredicate(
this.root,
this.cb,
ID,
JOB_NAME,
USER_NAME,
STATUSES,
TAGS,
CLUSTER_NAME,
CLUSTER,
COMMAND_NAME,
COMMAND,
MIN_STARTED,
MAX_STARTED,
MIN_FINISHED,
MAX_FINISHED,
GROUPING,
GROUPING_INSTANCE
);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.uniqueId), ID);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.name), JOB_NAME);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.user), USER_NAME);
for (final String status : STATUSES) {
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.status), status);
}
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.clusterName), CLUSTER_NAME);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.cluster), CLUSTER);
Mockito
.verify(this.cb, Mockito.times(1))
.like(this.root.get(JobEntity_.tagSearchString), this.tagLikeStatement);
Mockito.verify(this.cb, Mockito.times(1)).greaterThanOrEqualTo(this.root.get(JobEntity_.started), MIN_STARTED);
Mockito.verify(this.cb, Mockito.times(1)).lessThan(this.root.get(JobEntity_.started), MAX_STARTED);
Mockito
.verify(this.cb, Mockito.times(1))
.greaterThanOrEqualTo(this.root.get(JobEntity_.finished), MIN_FINISHED);
Mockito.verify(this.cb, Mockito.times(1)).lessThan(this.root.get(JobEntity_.finished), MAX_FINISHED);
}
@Test
void testFindWithOutGrouping() {
JobPredicates.getFindPredicate(
this.root,
this.cb,
ID,
JOB_NAME,
USER_NAME,
STATUSES,
TAGS,
CLUSTER_NAME,
CLUSTER,
COMMAND_NAME,
COMMAND,
MIN_STARTED,
MAX_STARTED,
MIN_FINISHED,
MAX_FINISHED,
null,
GROUPING_INSTANCE
);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.uniqueId), ID);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.name), JOB_NAME);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.user), USER_NAME);
for (final String status : STATUSES) {
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.status), status);
}
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.clusterName), CLUSTER_NAME);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.cluster), CLUSTER);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.commandName), COMMAND_NAME);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.command), COMMAND);
Mockito
.verify(this.cb, Mockito.times(1))
.like(this.root.get(JobEntity_.tagSearchString), this.tagLikeStatement);
Mockito.verify(this.cb, Mockito.times(1)).greaterThanOrEqualTo(this.root.get(JobEntity_.started), MIN_STARTED);
Mockito.verify(this.cb, Mockito.times(1)).lessThan(this.root.get(JobEntity_.started), MAX_STARTED);
Mockito
.verify(this.cb, Mockito.times(1))
.greaterThanOrEqualTo(this.root.get(JobEntity_.finished), MIN_FINISHED);
Mockito.verify(this.cb, Mockito.times(1)).lessThan(this.root.get(JobEntity_.finished), MAX_FINISHED);
Mockito.verify(this.cb, Mockito.never()).equal(this.root.get(JobEntity_.grouping), GROUPING);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.groupingInstance), GROUPING_INSTANCE);
}
@Test
void testFindWithOutGroupingInstance() {
JobPredicates.getFindPredicate(
this.root,
this.cb,
ID,
JOB_NAME,
USER_NAME,
STATUSES,
TAGS,
CLUSTER_NAME,
CLUSTER,
COMMAND_NAME,
COMMAND,
MIN_STARTED,
MAX_STARTED,
MIN_FINISHED,
MAX_FINISHED,
GROUPING,
null
);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.uniqueId), ID);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.name), JOB_NAME);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.user), USER_NAME);
for (final String status : STATUSES) {
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.status), status);
}
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.clusterName), CLUSTER_NAME);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.cluster), CLUSTER);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.commandName), COMMAND_NAME);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.command), COMMAND);
Mockito
.verify(this.cb, Mockito.times(1))
.like(this.root.get(JobEntity_.tagSearchString), this.tagLikeStatement);
Mockito.verify(this.cb, Mockito.times(1)).greaterThanOrEqualTo(this.root.get(JobEntity_.started), MIN_STARTED);
Mockito.verify(this.cb, Mockito.times(1)).lessThan(this.root.get(JobEntity_.started), MAX_STARTED);
Mockito
.verify(this.cb, Mockito.times(1))
.greaterThanOrEqualTo(this.root.get(JobEntity_.finished), MIN_FINISHED);
Mockito.verify(this.cb, Mockito.times(1)).lessThan(this.root.get(JobEntity_.finished), MAX_FINISHED);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(JobEntity_.grouping), GROUPING);
Mockito.verify(this.cb, Mockito.never()).equal(this.root.get(JobEntity_.groupingInstance), GROUPING_INSTANCE);
}
}
| 2,416 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/data/services/impl/jpa/queries
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/data/services/impl/jpa/queries/predicates/CommandPredicatesTest.java
|
/*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.genie.web.data.services.impl.jpa.queries.predicates;
import com.google.common.collect.Sets;
import com.netflix.genie.common.internal.dtos.CommandStatus;
import com.netflix.genie.web.data.services.impl.jpa.entities.CommandEntity;
import com.netflix.genie.web.data.services.impl.jpa.entities.CommandEntity_;
import com.netflix.genie.web.data.services.impl.jpa.entities.TagEntity;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.persistence.criteria.SetJoin;
import java.util.Set;
/**
* Tests for {@link CommandPredicates}.
*
* @author tgianos
*/
class CommandPredicatesTest {
private static final String NAME = "hive";
private static final String USER_NAME = "tgianos";
private static final TagEntity TAG_1 = new TagEntity("prod");
private static final TagEntity TAG_2 = new TagEntity("hive");
private static final TagEntity TAG_3 = new TagEntity("11");
private static final Set<TagEntity> TAGS = Sets.newHashSet(TAG_1, TAG_2, TAG_3);
private static final Set<String> STATUSES = Sets.newHashSet(
CommandStatus.ACTIVE.name(),
CommandStatus.INACTIVE.name()
);
private Root<CommandEntity> root;
private CriteriaQuery<?> cq;
private CriteriaBuilder cb;
private SetJoin<CommandEntity, TagEntity> tagEntityJoin;
@BeforeEach
@SuppressWarnings("unchecked")
void setup() {
this.root = (Root<CommandEntity>) Mockito.mock(Root.class);
this.cq = Mockito.mock(CriteriaQuery.class);
this.cb = Mockito.mock(CriteriaBuilder.class);
final Path<Long> idPath = (Path<Long>) Mockito.mock(Path.class);
Mockito.when(this.root.get(CommandEntity_.id)).thenReturn(idPath);
final Path<String> commandNamePath = (Path<String>) Mockito.mock(Path.class);
final Predicate equalNamePredicate = Mockito.mock(Predicate.class);
final Predicate likeNamePredicate = Mockito.mock(Predicate.class);
Mockito.when(this.root.get(CommandEntity_.name)).thenReturn(commandNamePath);
Mockito.when(this.cb.equal(commandNamePath, NAME)).thenReturn(equalNamePredicate);
Mockito.when(this.cb.like(commandNamePath, NAME)).thenReturn(likeNamePredicate);
final Path<String> userNamePath = (Path<String>) Mockito.mock(Path.class);
final Predicate equalUserNamePredicate = Mockito.mock(Predicate.class);
final Predicate likeUserNamePredicate = Mockito.mock(Predicate.class);
Mockito.when(this.root.get(CommandEntity_.user)).thenReturn(userNamePath);
Mockito.when(this.cb.equal(userNamePath, USER_NAME)).thenReturn(equalUserNamePredicate);
Mockito.when(this.cb.like(userNamePath, USER_NAME)).thenReturn(likeUserNamePredicate);
final Path<String> statusPath = (Path<String>) Mockito.mock(Path.class);
final Predicate equalStatusPredicate = Mockito.mock(Predicate.class);
Mockito.when(this.root.get(CommandEntity_.status)).thenReturn(statusPath);
Mockito
.when(this.cb.equal(Mockito.eq(statusPath), Mockito.anyString()))
.thenReturn(equalStatusPredicate);
this.tagEntityJoin = (SetJoin<CommandEntity, TagEntity>) Mockito.mock(SetJoin.class);
Mockito.when(this.root.join(CommandEntity_.tags)).thenReturn(this.tagEntityJoin);
final Predicate tagInPredicate = Mockito.mock(Predicate.class);
Mockito.when(this.tagEntityJoin.in(TAGS)).thenReturn(tagInPredicate);
final Expression<Long> idCountExpression = (Expression<Long>) Mockito.mock(Expression.class);
Mockito.when(this.cb.count(Mockito.any())).thenReturn(idCountExpression);
final Predicate havingPredicate = Mockito.mock(Predicate.class);
Mockito.when(this.cb.equal(idCountExpression, TAGS.size())).thenReturn(havingPredicate);
}
@Test
void testFindAll() {
CommandPredicates.find(this.root, this.cq, this.cb, NAME, USER_NAME, STATUSES, TAGS);
Mockito
.verify(this.cb, Mockito.times(1))
.equal(this.root.get(CommandEntity_.name), NAME);
Mockito
.verify(this.cb, Mockito.times(1))
.equal(this.root.get(CommandEntity_.user), USER_NAME);
for (final String status : STATUSES) {
Mockito
.verify(this.cb, Mockito.times(1))
.equal(this.root.get(CommandEntity_.status), status);
}
Mockito.verify(this.root, Mockito.times(1)).join(CommandEntity_.tags);
Mockito.verify(this.tagEntityJoin, Mockito.times(1)).in(TAGS);
Mockito.verify(this.cq, Mockito.times(1)).groupBy(Mockito.any(Path.class));
Mockito.verify(this.cq, Mockito.times(1)).having(Mockito.any(Predicate.class));
}
@Test
void testFindAllLike() {
final String newName = NAME + "%";
final String newUser = USER_NAME + "%";
CommandPredicates.find(this.root, this.cq, this.cb, newName, newUser, STATUSES, TAGS);
Mockito
.verify(this.cb, Mockito.times(1))
.like(this.root.get(CommandEntity_.name), newName);
Mockito
.verify(this.cb, Mockito.times(1))
.like(this.root.get(CommandEntity_.user), newUser);
for (final String status : STATUSES) {
Mockito
.verify(this.cb, Mockito.times(1))
.equal(this.root.get(CommandEntity_.status), status);
}
Mockito.verify(this.root, Mockito.times(1)).join(CommandEntity_.tags);
Mockito.verify(this.tagEntityJoin, Mockito.times(1)).in(TAGS);
Mockito.verify(this.cq, Mockito.times(1)).groupBy(Mockito.any(Path.class));
Mockito.verify(this.cq, Mockito.times(1)).having(Mockito.any(Predicate.class));
}
@Test
void testFindNoName() {
CommandPredicates.find(this.root, this.cq, this.cb, null, USER_NAME, STATUSES, TAGS);
Mockito
.verify(this.cb, Mockito.never())
.equal(this.root.get(CommandEntity_.name), NAME);
Mockito
.verify(this.cb, Mockito.times(1))
.equal(this.root.get(CommandEntity_.user), USER_NAME);
for (final String status : STATUSES) {
Mockito
.verify(this.cb, Mockito.times(1))
.equal(this.root.get(CommandEntity_.status), status);
}
Mockito.verify(this.root, Mockito.times(1)).join(CommandEntity_.tags);
Mockito.verify(this.tagEntityJoin, Mockito.times(1)).in(TAGS);
Mockito.verify(this.cq, Mockito.times(1)).groupBy(Mockito.any(Path.class));
Mockito.verify(this.cq, Mockito.times(1)).having(Mockito.any(Predicate.class));
}
@Test
void testFindNoUserName() {
CommandPredicates.find(this.root, this.cq, this.cb, NAME, null, STATUSES, TAGS);
Mockito
.verify(this.cb, Mockito.times(1))
.equal(this.root.get(CommandEntity_.name), NAME);
Mockito
.verify(this.cb, Mockito.never())
.equal(this.root.get(CommandEntity_.user), USER_NAME);
for (final String status : STATUSES) {
Mockito
.verify(this.cb, Mockito.times(1))
.equal(this.root.get(CommandEntity_.status), status);
}
Mockito.verify(this.root, Mockito.times(1)).join(CommandEntity_.tags);
Mockito.verify(this.tagEntityJoin, Mockito.times(1)).in(TAGS);
Mockito.verify(this.cq, Mockito.times(1)).groupBy(Mockito.any(Path.class));
Mockito.verify(this.cq, Mockito.times(1)).having(Mockito.any(Predicate.class));
}
@Test
void testFindNoTags() {
CommandPredicates.find(this.root, this.cq, this.cb, NAME, USER_NAME, STATUSES, null);
Mockito
.verify(this.cb, Mockito.times(1))
.equal(this.root.get(CommandEntity_.name), NAME);
Mockito
.verify(this.cb, Mockito.times(1))
.equal(this.root.get(CommandEntity_.user), USER_NAME);
for (final String status : STATUSES) {
Mockito
.verify(this.cb, Mockito.times(1))
.equal(this.root.get(CommandEntity_.status), status);
}
Mockito.verify(this.root, Mockito.never()).join(CommandEntity_.tags);
}
@Test
void testFindNoStatuses() {
CommandPredicates.find(this.root, this.cq, this.cb, NAME, USER_NAME, null, TAGS);
Mockito
.verify(this.cb, Mockito.times(1))
.equal(this.root.get(CommandEntity_.name), NAME);
Mockito
.verify(this.cb, Mockito.times(1))
.equal(this.root.get(CommandEntity_.user), USER_NAME);
for (final String status : STATUSES) {
Mockito
.verify(this.cb, Mockito.never())
.equal(this.root.get(CommandEntity_.status), status);
}
Mockito.verify(this.root, Mockito.times(1)).join(CommandEntity_.tags);
Mockito.verify(this.tagEntityJoin, Mockito.times(1)).in(TAGS);
Mockito.verify(this.cq, Mockito.times(1)).groupBy(Mockito.any(Path.class));
Mockito.verify(this.cq, Mockito.times(1)).having(Mockito.any(Predicate.class));
}
@Test
void testFindEmptyStatuses() {
CommandPredicates.find(this.root, this.cq, this.cb, NAME, USER_NAME, Sets.newHashSet(), TAGS);
Mockito
.verify(this.cb, Mockito.times(1))
.equal(this.root.get(CommandEntity_.name), NAME);
Mockito
.verify(this.cb, Mockito.times(1))
.equal(this.root.get(CommandEntity_.user), USER_NAME);
for (final String status : STATUSES) {
Mockito.verify(this.cb, Mockito.never()).equal(this.root.get(CommandEntity_.status), status);
}
Mockito.verify(this.root, Mockito.times(1)).join(CommandEntity_.tags);
Mockito.verify(this.tagEntityJoin, Mockito.times(1)).in(TAGS);
Mockito.verify(this.cq, Mockito.times(1)).groupBy(Mockito.any(Path.class));
Mockito.verify(this.cq, Mockito.times(1)).having(Mockito.any(Predicate.class));
}
}
| 2,417 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/data/services/impl/jpa/queries
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/data/services/impl/jpa/queries/predicates/ApplicationPredicatesTest.java
|
/*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.genie.web.data.services.impl.jpa.queries.predicates;
import com.google.common.collect.Sets;
import com.netflix.genie.common.internal.dtos.ApplicationStatus;
import com.netflix.genie.web.data.services.impl.jpa.entities.ApplicationEntity;
import com.netflix.genie.web.data.services.impl.jpa.entities.ApplicationEntity_;
import com.netflix.genie.web.data.services.impl.jpa.entities.TagEntity;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.persistence.criteria.SetJoin;
import java.util.Set;
import java.util.UUID;
/**
* Tests for {@link ApplicationPredicates}.
*
* @author tgianos
*/
class ApplicationPredicatesTest {
private static final String NAME = "tez";
private static final String USER_NAME = "tgianos";
private static final TagEntity TAG_1 = new TagEntity("tez");
private static final TagEntity TAG_2 = new TagEntity("yarn");
private static final TagEntity TAG_3 = new TagEntity("hadoop");
private static final Set<TagEntity> TAGS = Sets.newHashSet(TAG_1, TAG_2, TAG_3);
private static final Set<String> STATUSES = Sets.newHashSet(
ApplicationStatus.ACTIVE.name(),
ApplicationStatus.DEPRECATED.name()
);
private static final String TYPE = UUID.randomUUID().toString();
private Root<ApplicationEntity> root;
private CriteriaQuery<?> cq;
private CriteriaBuilder cb;
private SetJoin<ApplicationEntity, TagEntity> tagEntityJoin;
@BeforeEach
@SuppressWarnings("unchecked")
void setup() {
this.root = (Root<ApplicationEntity>) Mockito.mock(Root.class);
this.cq = Mockito.mock(CriteriaQuery.class);
this.cb = Mockito.mock(CriteriaBuilder.class);
final Path<Long> idPath = (Path<Long>) Mockito.mock(Path.class);
Mockito.when(this.root.get(ApplicationEntity_.id)).thenReturn(idPath);
final Path<String> namePath = (Path<String>) Mockito.mock(Path.class);
final Predicate equalNamePredicate = Mockito.mock(Predicate.class);
final Predicate likeNamePredicate = Mockito.mock(Predicate.class);
Mockito.when(this.root.get(ApplicationEntity_.name)).thenReturn(namePath);
Mockito.when(this.cb.equal(namePath, NAME)).thenReturn(equalNamePredicate);
Mockito.when(this.cb.like(namePath, NAME)).thenReturn(likeNamePredicate);
final Path<String> userNamePath = (Path<String>) Mockito.mock(Path.class);
final Predicate equalUserNamePredicate = Mockito.mock(Predicate.class);
final Predicate likeUserNamePredicate = Mockito.mock(Predicate.class);
Mockito.when(this.root.get(ApplicationEntity_.user)).thenReturn(userNamePath);
Mockito.when(this.cb.equal(userNamePath, USER_NAME)).thenReturn(equalUserNamePredicate);
Mockito.when(this.cb.like(userNamePath, USER_NAME)).thenReturn(likeUserNamePredicate);
final Path<String> statusPath = (Path<String>) Mockito.mock(Path.class);
final Predicate equalStatusPredicate = Mockito.mock(Predicate.class);
Mockito.when(this.root.get(ApplicationEntity_.status)).thenReturn(statusPath);
Mockito
.when(this.cb.equal(Mockito.eq(statusPath), Mockito.anyString()))
.thenReturn(equalStatusPredicate);
this.tagEntityJoin = (SetJoin<ApplicationEntity, TagEntity>) Mockito.mock(SetJoin.class);
Mockito.when(this.root.join(ApplicationEntity_.tags)).thenReturn(this.tagEntityJoin);
final Predicate tagInPredicate = Mockito.mock(Predicate.class);
Mockito.when(this.tagEntityJoin.in(TAGS)).thenReturn(tagInPredicate);
final Expression<Long> idCountExpression = (Expression<Long>) Mockito.mock(Expression.class);
Mockito.when(this.cb.count(Mockito.any())).thenReturn(idCountExpression);
final Predicate havingPredicate = Mockito.mock(Predicate.class);
Mockito.when(this.cb.equal(idCountExpression, TAGS.size())).thenReturn(havingPredicate);
final Path<String> typePath = (Path<String>) Mockito.mock(Path.class);
final Predicate equalTypePredicate = Mockito.mock(Predicate.class);
final Predicate likeTypePredicate = Mockito.mock(Predicate.class);
Mockito.when(this.root.get(ApplicationEntity_.type)).thenReturn(typePath);
Mockito.when(this.cb.equal(typePath, TYPE)).thenReturn(equalTypePredicate);
Mockito.when(this.cb.like(typePath, TYPE)).thenReturn(likeTypePredicate);
}
@Test
void testFindAll() {
ApplicationPredicates.find(this.root, this.cq, this.cb, NAME, USER_NAME, STATUSES, TAGS, TYPE);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(ApplicationEntity_.name), NAME);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(ApplicationEntity_.user), USER_NAME);
for (final String status : STATUSES) {
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(ApplicationEntity_.status), status);
}
// Tags
Mockito.verify(this.root, Mockito.times(1)).join(ApplicationEntity_.tags);
Mockito.verify(this.tagEntityJoin, Mockito.times(1)).in(TAGS);
Mockito.verify(this.cq, Mockito.times(1)).groupBy(Mockito.any(Path.class));
Mockito.verify(this.cq, Mockito.times(1)).having(Mockito.any(Predicate.class));
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(ApplicationEntity_.type), TYPE);
}
@Test
void testFindAllLike() {
final String newName = NAME + "%";
final String newUser = USER_NAME + "%";
final String newType = TYPE + "%";
ApplicationPredicates.find(this.root, this.cq, this.cb, newName, newUser, STATUSES, TAGS, newType);
Mockito.verify(this.cb, Mockito.times(1)).like(this.root.get(ApplicationEntity_.name), newName);
Mockito.verify(this.cb, Mockito.times(1)).like(this.root.get(ApplicationEntity_.user), newUser);
for (final String status : STATUSES) {
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(ApplicationEntity_.status), status);
}
Mockito.verify(this.root, Mockito.times(1)).join(ApplicationEntity_.tags);
Mockito.verify(this.tagEntityJoin, Mockito.times(1)).in(TAGS);
Mockito.verify(this.cq, Mockito.times(1)).groupBy(Mockito.any(Path.class));
Mockito.verify(this.cq, Mockito.times(1)).having(Mockito.any(Predicate.class));
Mockito.verify(this.cb, Mockito.times(1)).like(this.root.get(ApplicationEntity_.type), newType);
}
@Test
void testFindNoName() {
ApplicationPredicates.find(this.root, this.cq, this.cb, null, USER_NAME, STATUSES, TAGS, TYPE);
Mockito.verify(this.cb, Mockito.never()).equal(this.root.get(ApplicationEntity_.name), NAME);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(ApplicationEntity_.user), USER_NAME);
for (final String status : STATUSES) {
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(ApplicationEntity_.status), status);
}
Mockito.verify(this.root, Mockito.times(1)).join(ApplicationEntity_.tags);
Mockito.verify(this.tagEntityJoin, Mockito.times(1)).in(TAGS);
Mockito.verify(this.cq, Mockito.times(1)).groupBy(Mockito.any(Path.class));
Mockito.verify(this.cq, Mockito.times(1)).having(Mockito.any(Predicate.class));
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(ApplicationEntity_.type), TYPE);
}
@Test
void testFindNoUserName() {
ApplicationPredicates.find(this.root, this.cq, this.cb, NAME, null, STATUSES, TAGS, TYPE);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(ApplicationEntity_.name), NAME);
Mockito.verify(this.cb, Mockito.never()).equal(this.root.get(ApplicationEntity_.user), USER_NAME);
for (final String status : STATUSES) {
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(ApplicationEntity_.status), status);
}
Mockito.verify(this.root, Mockito.times(1)).join(ApplicationEntity_.tags);
Mockito.verify(this.tagEntityJoin, Mockito.times(1)).in(TAGS);
Mockito.verify(this.cq, Mockito.times(1)).groupBy(Mockito.any(Path.class));
Mockito.verify(this.cq, Mockito.times(1)).having(Mockito.any(Predicate.class));
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(ApplicationEntity_.type), TYPE);
}
@Test
void testFindNoStatuses() {
ApplicationPredicates.find(this.root, this.cq, this.cb, NAME, USER_NAME, null, TAGS, TYPE);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(ApplicationEntity_.name), NAME);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(ApplicationEntity_.user), USER_NAME);
for (final String status : STATUSES) {
Mockito.verify(this.cb, Mockito.never()).equal(this.root.get(ApplicationEntity_.status), status);
}
Mockito.verify(this.root, Mockito.times(1)).join(ApplicationEntity_.tags);
Mockito.verify(this.tagEntityJoin, Mockito.times(1)).in(TAGS);
Mockito.verify(this.cq, Mockito.times(1)).groupBy(Mockito.any(Path.class));
Mockito.verify(this.cq, Mockito.times(1)).having(Mockito.any(Predicate.class));
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(ApplicationEntity_.type), TYPE);
}
@Test
void testFindEmptyStatuses() {
ApplicationPredicates.find(this.root, this.cq, this.cb, NAME, USER_NAME, Sets.newHashSet(), TAGS, TYPE);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(ApplicationEntity_.name), NAME);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(ApplicationEntity_.user), USER_NAME);
for (final String status : STATUSES) {
Mockito.verify(this.cb, Mockito.never()).equal(this.root.get(ApplicationEntity_.status), status);
}
Mockito.verify(this.root, Mockito.times(1)).join(ApplicationEntity_.tags);
Mockito.verify(this.tagEntityJoin, Mockito.times(1)).in(TAGS);
Mockito.verify(this.cq, Mockito.times(1)).groupBy(Mockito.any(Path.class));
Mockito.verify(this.cq, Mockito.times(1)).having(Mockito.any(Predicate.class));
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(ApplicationEntity_.type), TYPE);
}
@Test
void testFindNoTags() {
ApplicationPredicates.find(this.root, this.cq, this.cb, NAME, USER_NAME, STATUSES, null, TYPE);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(ApplicationEntity_.name), NAME);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(ApplicationEntity_.user), USER_NAME);
for (final String status : STATUSES) {
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(ApplicationEntity_.status), status);
}
Mockito.verify(this.root, Mockito.never()).join(ApplicationEntity_.tags);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(ApplicationEntity_.type), TYPE);
}
@Test
void testFindNoType() {
ApplicationPredicates.find(this.root, this.cq, this.cb, NAME, USER_NAME, STATUSES, TAGS, null);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(ApplicationEntity_.name), NAME);
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(ApplicationEntity_.user), USER_NAME);
for (final String status : STATUSES) {
Mockito.verify(this.cb, Mockito.times(1)).equal(this.root.get(ApplicationEntity_.status), status);
}
Mockito.verify(this.root, Mockito.times(1)).join(ApplicationEntity_.tags);
Mockito.verify(this.tagEntityJoin, Mockito.times(1)).in(TAGS);
Mockito.verify(this.cq, Mockito.times(1)).groupBy(Mockito.any(Path.class));
Mockito.verify(this.cq, Mockito.times(1)).having(Mockito.any(Predicate.class));
Mockito.verify(this.cb, Mockito.never()).equal(this.root.get(ApplicationEntity_.type), TYPE);
}
}
| 2,418 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/data/services/impl/jpa/queries
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/data/services/impl/jpa/queries/predicates/package-info.java
|
/*
*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Classes to test JPA specification classes.
*
* @author tgianos
*/
package com.netflix.genie.web.data.services.impl.jpa.queries.predicates;
| 2,419 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/data/services/impl/jpa
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/data/services/impl/jpa/entities/ApplicationEntityTest.java
|
/*
*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.data.services.impl.jpa.entities;
import com.google.common.collect.Sets;
import com.netflix.genie.common.internal.dtos.ApplicationStatus;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import javax.validation.ConstraintViolationException;
import java.util.Set;
/**
* Test the Application class.
*
* @author tgianos
*/
class ApplicationEntityTest extends EntityTestBase {
private static final String NAME = "pig";
private static final String USER = "tgianos";
private static final String VERSION = "1.0";
private ApplicationEntity a;
/**
* Setup the tests.
*/
@BeforeEach
void setup() {
this.a = new ApplicationEntity();
this.a.setName(NAME);
this.a.setUser(USER);
this.a.setVersion(VERSION);
this.a.setStatus(ApplicationStatus.ACTIVE.name());
}
/**
* Test the default Constructor.
*/
@Test
void testDefaultConstructor() {
final ApplicationEntity entity = new ApplicationEntity();
Assertions.assertThat(entity.getSetupFile()).isNotPresent();
Assertions.assertThat(entity.getStatus()).isNull();
Assertions.assertThat(entity.getName()).isNull();
Assertions.assertThat(entity.getUser()).isNull();
Assertions.assertThat(entity.getVersion()).isNull();
Assertions.assertThat(entity.getDependencies()).isEmpty();
Assertions.assertThat(entity.getConfigs()).isEmpty();
Assertions.assertThat(entity.getTags()).isEmpty();
Assertions.assertThat(entity.getCommands()).isEmpty();
}
/**
* Make sure validation works on valid apps.
*/
@Test
void testValidate() {
this.a.setName(NAME);
this.a.setUser(USER);
this.a.setVersion(VERSION);
this.a.setStatus(ApplicationStatus.ACTIVE.name());
this.validate(this.a);
}
/**
* Make sure validation works on with failure from super class.
*/
@Test
void testValidateNoName() {
this.a.setName("");
Assertions
.assertThatExceptionOfType(ConstraintViolationException.class)
.isThrownBy(() -> this.validate(this.a));
}
/**
* Make sure validation works on with failure from super class.
*/
@Test
void testValidateNoUser() {
this.a.setUser("");
Assertions
.assertThatExceptionOfType(ConstraintViolationException.class)
.isThrownBy(() -> this.validate(this.a));
}
/**
* Make sure validation works on with failure from super class.
*/
@Test
void testValidateNoVersion() {
this.a.setVersion("");
Assertions
.assertThatExceptionOfType(ConstraintViolationException.class)
.isThrownBy(() -> this.validate(this.a));
}
/**
* Test setting the status.
*/
@Test
void testSetStatus() {
this.a.setStatus(ApplicationStatus.ACTIVE.name());
Assertions.assertThat(this.a.getStatus()).isEqualTo(ApplicationStatus.ACTIVE.name());
}
/**
* Test setting the setup file.
*/
@Test
void testSetSetupFile() {
Assertions.assertThat(this.a.getSetupFile()).isNotPresent();
final FileEntity setupFileEntity = new FileEntity("s3://netflix.propFile");
this.a.setSetupFile(setupFileEntity);
Assertions.assertThat(this.a.getSetupFile()).isPresent().contains(setupFileEntity);
}
/**
* Test setting the configs.
*/
@Test
void testSetConfigs() {
final Set<FileEntity> configs = Sets.newHashSet(new FileEntity("s3://netflix.configFile"));
this.a.setConfigs(configs);
Assertions.assertThat(this.a.getConfigs()).isEqualTo(configs);
this.a.setConfigs(null);
Assertions.assertThat(this.a.getConfigs()).isEmpty();
}
/**
* Test setting the jars.
*/
@Test
void testSetDependencies() {
final Set<FileEntity> dependencies = Sets.newHashSet(new FileEntity("s3://netflix/jars/myJar.jar"));
this.a.setDependencies(dependencies);
Assertions.assertThat(this.a.getDependencies()).isEqualTo(dependencies);
this.a.setDependencies(null);
Assertions.assertThat(this.a.getDependencies()).isEmpty();
}
/**
* Test setting the tags.
*/
@Test
void testSetTags() {
final TagEntity tag1 = new TagEntity("tag1");
final TagEntity tag2 = new TagEntity("tag2");
final Set<TagEntity> tags = Sets.newHashSet(tag1, tag2);
this.a.setTags(tags);
Assertions.assertThat(this.a.getTags()).isEqualTo(tags);
this.a.setTags(null);
Assertions.assertThat(this.a.getTags()).isEmpty();
}
/**
* Test setting the commands.
*/
@Test
void testSetCommands() {
final Set<CommandEntity> commandEntities = Sets.newHashSet(new CommandEntity());
this.a.setCommands(commandEntities);
Assertions.assertThat(this.a.getCommands()).isEqualTo(commandEntities);
this.a.setCommands(null);
Assertions.assertThat(this.a.getCommands()).isEmpty();
}
/**
* Test the toString method.
*/
@Test
void testToString() {
Assertions.assertThat(this.a.toString()).isNotBlank();
}
}
| 2,420 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/data/services/impl/jpa
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/data/services/impl/jpa/entities/JobEntityTest.java
|
/*
*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.data.services.impl.jpa.entities;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.netflix.genie.common.internal.dtos.JobStatus;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import javax.validation.ConstraintViolationException;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
/**
* Tests for {@link JobEntity}.
*
* @author amsharma
* @author tgianos
*/
class JobEntityTest extends EntityTestBase {
private static final String USER = "tgianos";
private static final String NAME = "TomsJob";
private static final String VERSION = "1.2.3";
private JobEntity entity;
@BeforeEach
void setup() {
this.entity = new JobEntity();
this.entity.setUser(USER);
this.entity.setName(NAME);
this.entity.setVersion(VERSION);
}
@Test
void testDefaultConstructor() {
final JobEntity localJobEntity = new JobEntity();
Assertions.assertThat(localJobEntity.getUniqueId()).isNotBlank();
}
@Test
void testConstructor() {
Assertions.assertThat(this.entity.getUniqueId()).isNotBlank();
Assertions.assertThat(NAME).isEqualTo(this.entity.getName());
Assertions.assertThat(USER).isEqualTo(this.entity.getUser());
Assertions.assertThat(this.entity.getVersion()).isEqualTo(VERSION);
}
@Test
void testOnCreateJob() {
Assertions.assertThat(this.entity.getTagSearchString()).isNull();
this.entity.onCreateJob();
Assertions.assertThat(this.entity.getTagSearchString()).isNull();
final TagEntity one = new TagEntity("abc");
final TagEntity two = new TagEntity("def");
final TagEntity three = new TagEntity("ghi");
this.entity.setTags(Sets.newHashSet(three, two, one));
this.entity.onCreateJob();
Assertions.assertThat(this.entity.getTagSearchString()).isEqualTo("|abc||def||ghi|");
}
@Test
void testSetGetClusterName() {
this.testOptionalField(
this.entity::getClusterName,
this.entity::setClusterName,
UUID.randomUUID().toString()
);
}
@Test
void testSetGetCommandName() {
this.testOptionalField(
this.entity::getCommandName,
this.entity::setCommandName,
UUID.randomUUID().toString()
);
}
@Test
void testSetGetCommandArgs() {
Assertions.assertThat(this.entity.getCommandArgs()).isEmpty();
this.entity.setCommandArgs(null);
Assertions.assertThat(this.entity.getCommandArgs()).isEmpty();
final List<String> commandArgs = Lists.newArrayList();
this.entity.setCommandArgs(commandArgs);
Assertions.assertThat(this.entity.getCommandArgs()).isEmpty();
commandArgs.add(UUID.randomUUID().toString());
this.entity.setCommandArgs(commandArgs);
Assertions.assertThat(this.entity.getCommandArgs()).isEqualTo(commandArgs);
}
@Test
void testSetGetStatus() {
Assertions.assertThat(this.entity.getStatus()).isNull();
this.entity.setStatus(JobStatus.KILLED.name());
Assertions.assertThat(this.entity.getStatus()).isEqualTo(JobStatus.KILLED.name());
}
@Test
void testSetGetStatusMsg() {
this.testOptionalField(this.entity::getStatusMsg, this.entity::setStatusMsg, UUID.randomUUID().toString());
}
@Test
void testSetGetStarted() {
this.testOptionalField(this.entity::getStarted, this.entity::setStarted, Instant.ofEpochMilli(123453L));
}
@Test
void testSetGetFinished() {
this.testOptionalField(this.entity::getFinished, this.entity::setFinished, Instant.ofEpochMilli(123453L));
}
@Test
void testSetGetArchiveLocation() {
this.testOptionalField(
this.entity::getArchiveLocation,
this.entity::setArchiveLocation,
UUID.randomUUID().toString()
);
}
@Test
void testSetNotifiedJobStatus() {
final JobEntity localJobEntity = new JobEntity();
Assertions.assertThat(localJobEntity.getNotifiedJobStatus()).isNotPresent();
localJobEntity.setNotifiedJobStatus(JobStatus.RUNNING.name());
Assertions.assertThat(localJobEntity.getNotifiedJobStatus()).isPresent().contains(JobStatus.RUNNING.name());
}
@Test
void testSetGetTags() {
Assertions.assertThat(this.entity.getTags()).isEmpty();
final TagEntity one = new TagEntity("someTag");
final TagEntity two = new TagEntity("someOtherTag");
final Set<TagEntity> tags = Sets.newHashSet(one, two);
this.entity.setTags(tags);
Assertions.assertThat(this.entity.getTags()).isEqualTo(tags);
this.entity.setTags(null);
Assertions.assertThat(this.entity.getTags()).isEmpty();
}
@Test
void testValidate() {
this.validate(this.entity);
}
@Test
void testValidateBadSuperClass() {
Assertions
.assertThatExceptionOfType(ConstraintViolationException.class)
.isThrownBy(() -> this.validate(new JobEntity()));
}
@Test
void canSetCluster() {
final ClusterEntity cluster = new ClusterEntity();
final String clusterName = UUID.randomUUID().toString();
cluster.setName(clusterName);
Assertions.assertThat(this.entity.getCluster()).isNotPresent();
Assertions.assertThat(this.entity.getClusterName()).isNotPresent();
this.entity.setCluster(cluster);
Assertions.assertThat(this.entity.getCluster()).isPresent().contains(cluster);
Assertions.assertThat(this.entity.getClusterName()).isPresent().contains(clusterName);
this.entity.setCluster(null);
Assertions.assertThat(this.entity.getCluster()).isNotPresent();
Assertions.assertThat(this.entity.getClusterName()).isNotPresent();
}
@Test
void canSetCommand() {
final CommandEntity command = new CommandEntity();
final String commandName = UUID.randomUUID().toString();
command.setName(commandName);
Assertions.assertThat(this.entity.getCommand()).isNotPresent();
Assertions.assertThat(this.entity.getCommandName()).isNotPresent();
this.entity.setCommand(command);
Assertions.assertThat(this.entity.getCommand()).isPresent().contains(command);
Assertions.assertThat(this.entity.getCommandName()).isPresent().contains(commandName);
this.entity.setCommand(null);
Assertions.assertThat(this.entity.getCommand()).isNotPresent();
Assertions.assertThat(this.entity.getCommandName()).isNotPresent();
}
@Test
void canSetApplications() {
final ApplicationEntity application1 = new ApplicationEntity();
application1.setUniqueId(UUID.randomUUID().toString());
final ApplicationEntity application2 = new ApplicationEntity();
application2.setUniqueId(UUID.randomUUID().toString());
final ApplicationEntity application3 = new ApplicationEntity();
application3.setUniqueId(UUID.randomUUID().toString());
final List<ApplicationEntity> applications = Lists.newArrayList(application1, application2, application3);
Assertions.assertThat(this.entity.getApplications()).isEmpty();
this.entity.setApplications(applications);
Assertions.assertThat(this.entity.getApplications()).isEqualTo(applications);
}
@Test
void canSetAgentHostName() {
this.testOptionalField(
this.entity::getAgentHostname,
this.entity::setAgentHostname,
UUID.randomUUID().toString()
);
}
@Test
void canSetProcessId() {
this.testOptionalField(this.entity::getProcessId, this.entity::setProcessId, 352);
}
@Test
void canSetExitCode() {
this.testOptionalField(this.entity::getExitCode, this.entity::setExitCode, 80072043);
}
@Test
void canSetMemoryUsed() {
this.testOptionalField(this.entity::getMemoryUsed, this.entity::setMemoryUsed, 10_240L);
}
@Test
void canSetRequestApiClientHostname() {
this.testOptionalField(
this.entity::getRequestApiClientHostname,
this.entity::setRequestApiClientHostname,
UUID.randomUUID().toString()
);
}
@Test
void canSetRequestApiClientUserAgent() {
this.testOptionalField(
this.entity::getRequestApiClientUserAgent,
this.entity::setRequestApiClientUserAgent,
UUID.randomUUID().toString()
);
}
@Test
void canSetRequestAgentClientHostname() {
this.testOptionalField(
this.entity::getRequestAgentClientHostname,
this.entity::setRequestAgentClientHostname,
UUID.randomUUID().toString()
);
}
@Test
void canSetRequestAgentClientVersion() {
this.testOptionalField(
this.entity::getRequestAgentClientVersion,
this.entity::setRequestAgentClientVersion,
UUID.randomUUID().toString()
);
}
@Test
void canSetRequestAgentClientPid() {
this.testOptionalField(this.entity::getRequestAgentClientPid, this.entity::setRequestAgentClientPid, 28_000);
}
@Test
void canSetNumAttachments() {
this.testOptionalField(this.entity::getNumAttachments, this.entity::setNumAttachments, 380_208);
}
@Test
void canSetTotalSizeOfAttachments() {
this.testOptionalField(
this.entity::getTotalSizeOfAttachments,
this.entity::setTotalSizeOfAttachments,
90832432L
);
}
@Test
void canSetStdOutSize() {
this.testOptionalField(this.entity::getStdOutSize, this.entity::setStdOutSize, 90334432L);
}
@Test
void canSetStdErrSize() {
this.testOptionalField(this.entity::getStdErrSize, this.entity::setStdErrSize, 9089932L);
}
@Test
void canSetGroup() {
this.testOptionalField(
this.entity::getGenieUserGroup,
this.entity::setGenieUserGroup,
UUID.randomUUID().toString()
);
}
@Test
void canSetClusterCriteria() {
final Set<TagEntity> one = Sets.newHashSet("one", "two", "three")
.stream()
.map(TagEntity::new)
.collect(Collectors.toSet());
final Set<TagEntity> two = Sets.newHashSet("four", "five", "six")
.stream()
.map(TagEntity::new)
.collect(Collectors.toSet());
final Set<TagEntity> three = Sets.newHashSet("seven", "eight", "nine")
.stream()
.map(TagEntity::new)
.collect(Collectors.toSet());
final CriterionEntity entity1 = new CriterionEntity(null, null, null, null, one);
final CriterionEntity entity2 = new CriterionEntity(null, null, null, null, two);
final CriterionEntity entity3 = new CriterionEntity(null, null, null, null, three);
final List<CriterionEntity> clusterCriteria = Lists.newArrayList(entity1, entity2, entity3);
this.entity.setClusterCriteria(clusterCriteria);
Assertions.assertThat(this.entity.getClusterCriteria()).isEqualTo(clusterCriteria);
}
@Test
void canSetNullClusterCriteria() {
this.entity.setClusterCriteria(null);
Assertions.assertThat(this.entity.getClusterCriteria()).isEmpty();
}
@Test
void canSetConfigs() {
final Set<FileEntity> configs = Sets.newHashSet(new FileEntity(UUID.randomUUID().toString()));
this.entity.setConfigs(configs);
Assertions.assertThat(this.entity.getConfigs()).isEqualTo(configs);
}
@Test
void canSetNullConfigs() {
this.entity.setConfigs(null);
Assertions.assertThat(this.entity.getConfigs()).isEmpty();
}
@Test
void canSetDependencies() {
final Set<FileEntity> dependencies = Sets.newHashSet(new FileEntity(UUID.randomUUID().toString()));
this.entity.setDependencies(dependencies);
Assertions.assertThat(this.entity.getDependencies()).isEqualTo(dependencies);
}
@Test
void canSetNullDependencies() {
this.entity.setDependencies(null);
Assertions.assertThat(this.entity.getDependencies()).isEmpty();
}
@Test
void canSetArchivingDisabled() {
this.entity.setArchivingDisabled(true);
Assertions.assertThat(this.entity.isArchivingDisabled()).isTrue();
}
@Test
void canSetEmail() {
this.testOptionalField(this.entity::getEmail, this.entity::setEmail, UUID.randomUUID().toString());
}
@Test
void canSetCommandCriteria() {
final Set<TagEntity> tags = Sets.newHashSet(
new TagEntity(UUID.randomUUID().toString()),
new TagEntity(UUID.randomUUID().toString())
);
final CriterionEntity commandCriterion = new CriterionEntity(null, null, null, null, tags);
this.entity.setCommandCriterion(commandCriterion);
Assertions.assertThat(this.entity.getCommandCriterion()).isEqualTo(commandCriterion);
}
@Test
void canSetSetupFile() {
final FileEntity setupFileEntity = new FileEntity(UUID.randomUUID().toString());
this.entity.setSetupFile(setupFileEntity);
Assertions.assertThat(this.entity.getSetupFile()).isPresent().contains(setupFileEntity);
}
@Test
void canSetTags() {
final TagEntity one = new TagEntity(UUID.randomUUID().toString());
final TagEntity two = new TagEntity(UUID.randomUUID().toString());
final Set<TagEntity> tags = Sets.newHashSet(one, two);
this.entity.setTags(tags);
Assertions.assertThat(this.entity.getTags()).isEqualTo(tags);
this.entity.setTags(null);
Assertions.assertThat(this.entity.getTags()).isEmpty();
}
@Test
void canSetRequestedCpu() {
this.testOptionalField(this.entity::getRequestedCpu, this.entity::setRequestedCpu, 16);
}
@Test
void canSetRequestedMemory() {
this.testOptionalField(this.entity::getRequestedMemory, this.entity::setRequestedMemory, 2048L);
}
@Test
void canSetRequestedApplications() {
final String application = UUID.randomUUID().toString();
final List<String> applications = Lists.newArrayList(application);
this.entity.setRequestedApplications(applications);
Assertions.assertThat(this.entity.getRequestedApplications()).isEqualTo(applications);
}
@Test
void canSetRequestedTimeout() {
this.testOptionalField(this.entity::getRequestedTimeout, this.entity::setRequestedTimeout, 28023423);
}
@Test
void canSetRequestedEnvironmentVariables() {
Assertions.assertThat(this.entity.getRequestedEnvironmentVariables()).isEmpty();
this.entity.setRequestedEnvironmentVariables(null);
Assertions.assertThat(this.entity.getRequestedEnvironmentVariables()).isEmpty();
final Map<String, String> variables = Maps.newHashMap();
variables.put(UUID.randomUUID().toString(), UUID.randomUUID().toString());
this.entity.setRequestedEnvironmentVariables(variables);
Assertions.assertThat(this.entity.getRequestedEnvironmentVariables()).isEqualTo(variables);
// Make sure outside modifications of collection don't affect internal class state
variables.put(UUID.randomUUID().toString(), UUID.randomUUID().toString());
Assertions.assertThat(this.entity.getRequestedEnvironmentVariables()).isNotEqualTo(variables);
this.entity.setRequestedEnvironmentVariables(variables);
Assertions.assertThat(this.entity.getRequestedEnvironmentVariables()).isEqualTo(variables);
// Make sure this clears variables
this.entity.setRequestedEnvironmentVariables(null);
Assertions.assertThat(this.entity.getRequestedEnvironmentVariables()).isEmpty();
}
@Test
void canSetEnvironmentVariables() {
Assertions.assertThat(this.entity.getEnvironmentVariables()).isEmpty();
this.entity.setEnvironmentVariables(null);
Assertions.assertThat(this.entity.getEnvironmentVariables()).isEmpty();
final Map<String, String> variables = Maps.newHashMap();
variables.put(UUID.randomUUID().toString(), UUID.randomUUID().toString());
this.entity.setEnvironmentVariables(variables);
Assertions.assertThat(this.entity.getEnvironmentVariables()).isEqualTo(variables);
// Make sure outside modifications of collection don't affect internal class state
variables.put(UUID.randomUUID().toString(), UUID.randomUUID().toString());
Assertions.assertThat(this.entity.getEnvironmentVariables()).isNotEqualTo(variables);
this.entity.setEnvironmentVariables(variables);
Assertions.assertThat(this.entity.getEnvironmentVariables()).isEqualTo(variables);
// Make sure this clears variables
this.entity.setEnvironmentVariables(null);
Assertions.assertThat(this.entity.getEnvironmentVariables()).isEmpty();
}
@Test
void canSetInteractive() {
Assertions.assertThat(this.entity.isInteractive()).isFalse();
this.entity.setInteractive(true);
Assertions.assertThat(this.entity.isInteractive()).isTrue();
}
@Test
void canSetResolved() {
Assertions.assertThat(this.entity.isResolved()).isFalse();
this.entity.setResolved(true);
Assertions.assertThat(this.entity.isResolved()).isTrue();
}
@Test
void canSetRequestedJobDirectoryLocation() {
this.testOptionalField(
this.entity::getRequestedJobDirectoryLocation,
this.entity::setRequestedJobDirectoryLocation,
UUID.randomUUID().toString()
);
}
@Test
void canSetJobDirectoryLocation() {
this.testOptionalField(
this.entity::getJobDirectoryLocation,
this.entity::setJobDirectoryLocation,
UUID.randomUUID().toString()
);
}
@Test
void canSetRequestedAgentConfigExt() {
this.testOptionalField(
this.entity::getRequestedAgentConfigExt,
this.entity::setRequestedAgentConfigExt,
Mockito.mock(JsonNode.class)
);
}
@Test
void canSetRequestedAgentEnvironmentExt() {
this.testOptionalField(
this.entity::getRequestedAgentEnvironmentExt,
this.entity::setRequestedAgentEnvironmentExt,
Mockito.mock(JsonNode.class)
);
}
@Test
void canSetAgentVersion() {
this.testOptionalField(
this.entity::getAgentVersion,
this.entity::setAgentVersion,
UUID.randomUUID().toString()
);
}
@Test
void canSetAgentPid() {
this.testOptionalField(this.entity::getAgentPid, this.entity::setAgentPid, 31_382);
}
@Test
void canSetClaimed() {
Assertions.assertThat(this.entity.isClaimed()).isFalse();
this.entity.setClaimed(true);
Assertions.assertThat(this.entity.isClaimed()).isTrue();
}
@Test
void canSetTimeoutUsed() {
this.testOptionalField(this.entity::getTimeoutUsed, this.entity::setTimeoutUsed, 324_323);
}
@Test
void canSetApi() {
Assertions.assertThat(this.entity.isApi()).isTrue();
this.entity.setApi(false);
Assertions.assertThat(this.entity.isApi()).isFalse();
}
@Test
void canSetArchiveStatus() {
this.testOptionalField(
this.entity::getArchiveStatus,
this.entity::setArchiveStatus,
UUID.randomUUID().toString()
);
}
@Test
void canSetRequestedLauncherExt() {
this.testOptionalField(
this.entity::getRequestedLauncherExt,
this.entity::setRequestedLauncherExt,
Mockito.mock(JsonNode.class)
);
}
@Test
void canSetLauncherExt() {
this.testOptionalField(this.entity::getLauncherExt, this.entity::setLauncherExt, Mockito.mock(JsonNode.class));
}
@Test
void canSetCpuUsed() {
this.testOptionalField(this.entity::getCpuUsed, this.entity::setCpuUsed, 42);
}
@Test
void canSetGpuRequested() {
this.testOptionalField(this.entity::getRequestedGpu, this.entity::setRequestedGpu, 24);
}
@Test
void canSetGpuUsed() {
this.testOptionalField(this.entity::getGpuUsed, this.entity::setGpuUsed, 242524);
}
@Test
void canSetRequestedDiskMb() {
this.testOptionalField(this.entity::getRequestedDiskMb, this.entity::setRequestedDiskMb, 1_5234L);
}
@Test
void canSetDiskMbUsed() {
this.testOptionalField(this.entity::getDiskMbUsed, this.entity::setDiskMbUsed, 1_234L);
}
@Test
void canSetRequestedNetworkMbps() {
this.testOptionalField(this.entity::getRequestedNetworkMbps, this.entity::setRequestedNetworkMbps, 52L);
}
@Test
void canSetNetworkMbpsUsed() {
this.testOptionalField(this.entity::getNetworkMbpsUsed, this.entity::setNetworkMbpsUsed, 521L);
}
@Test
void canSetRequestedImages() {
this.testOptionalField(
this.entity::getRequestedImages,
this.entity::setRequestedImages,
Mockito.mock(JsonNode.class)
);
}
@Test
void canSetImageNameUsed() {
this.testOptionalField(
this.entity::getImagesUsed,
this.entity::setImagesUsed,
Mockito.mock(JsonNode.class)
);
}
@Test
void testToString() {
Assertions.assertThat(this.entity.toString()).isNotBlank();
}
}
| 2,421 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/data/services/impl/jpa
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/data/services/impl/jpa/entities/CriterionEntityTest.java
|
/*
*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.data.services.impl.jpa.entities;
import com.google.common.collect.Sets;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.Set;
import java.util.UUID;
/**
* Tests for the CriterionEntity class.
*
* @author tgianos
* @since 3.3.0
*/
class CriterionEntityTest extends EntityTestBase {
/**
* Make sure the argument constructor sets the tags argument.
*/
@Test
void canCreateCriterionEntityWithTags() {
CriterionEntity entity = new CriterionEntity(null, null, null, null, null);
Assertions.assertThat(entity.getTags()).isEmpty();
final Set<TagEntity> tags = Sets.newHashSet();
entity = new CriterionEntity(null, null, null, null, tags);
Assertions.assertThat(entity.getTags()).isEmpty();
tags.add(new TagEntity(UUID.randomUUID().toString()));
tags.add(new TagEntity(UUID.randomUUID().toString()));
entity = new CriterionEntity(null, null, null, null, tags);
Assertions.assertThat(entity.getTags()).isEqualTo(tags);
}
/**
* Make sure we can create a criterion.
*/
@Test
void canCreateCriterionEntity() {
final CriterionEntity entity = new CriterionEntity();
Assertions.assertThat(entity.getUniqueId()).isNotPresent();
Assertions.assertThat(entity.getName()).isNotPresent();
Assertions.assertThat(entity.getVersion()).isNotPresent();
Assertions.assertThat(entity.getStatus()).isNotPresent();
Assertions.assertThat(entity.getTags()).isEmpty();
}
/**
* Make sure setter is using the right field.
*/
@Test
void canSetUniqueId() {
final CriterionEntity entity = new CriterionEntity();
Assertions.assertThat(entity.getUniqueId()).isNotPresent();
final String uniqueId = UUID.randomUUID().toString();
entity.setUniqueId(uniqueId);
Assertions.assertThat(entity.getUniqueId()).isPresent().contains(uniqueId);
}
/**
* Make sure setter is using the right field.
*/
@Test
void canSetName() {
final CriterionEntity entity = new CriterionEntity();
Assertions.assertThat(entity.getName()).isNotPresent();
final String name = UUID.randomUUID().toString();
entity.setName(name);
Assertions.assertThat(entity.getName()).isPresent().contains(name);
}
/**
* Make sure setter is using the right field.
*/
@Test
void canSetVersion() {
final CriterionEntity entity = new CriterionEntity();
Assertions.assertThat(entity.getVersion()).isNotPresent();
final String version = UUID.randomUUID().toString();
entity.setVersion(version);
Assertions.assertThat(entity.getVersion()).isPresent().contains(version);
}
/**
* Make sure setter is using the right field.
*/
@Test
void canSetStatus() {
final CriterionEntity entity = new CriterionEntity();
Assertions.assertThat(entity.getStatus()).isNotPresent();
final String status = UUID.randomUUID().toString();
entity.setStatus(status);
Assertions.assertThat(entity.getStatus()).isPresent().contains(status);
}
/**
* Make sure setting the tags works.
*/
@Test
void canSetTags() {
final CriterionEntity entity = new CriterionEntity();
Assertions.assertThat(entity.getTags()).isEmpty();
entity.setTags(null);
Assertions.assertThat(entity.getTags()).isEmpty();
final Set<TagEntity> tags = Sets.newHashSet();
entity.setTags(tags);
Assertions.assertThat(entity.getTags()).isEmpty();
tags.add(new TagEntity(UUID.randomUUID().toString()));
entity.setTags(tags);
Assertions.assertThat(entity.getTags()).isEqualTo(tags);
}
/**
* Test to make sure equals and hash code only care about the id of the base class not the tags.
*/
@Test
void testEqualsAndHashCode() {
final Set<TagEntity> tags = Sets.newHashSet(
new TagEntity(UUID.randomUUID().toString()),
new TagEntity(UUID.randomUUID().toString())
);
final CriterionEntity one = new CriterionEntity(null, null, null, null, tags);
final CriterionEntity two = new CriterionEntity(null, null, null, null, tags);
final CriterionEntity three = new CriterionEntity();
Assertions.assertThat(one).isEqualTo(two);
Assertions.assertThat(one).isEqualTo(three);
Assertions.assertThat(two).isEqualTo(three);
Assertions.assertThat(one.hashCode()).isEqualTo(two.hashCode());
Assertions.assertThat(one.hashCode()).isEqualTo(three.hashCode());
Assertions.assertThat(two.hashCode()).isEqualTo(three.hashCode());
}
/**
* Test the toString method.
*/
@Test
void testToString() {
Assertions.assertThat(new CriterionEntity().toString()).isNotBlank();
}
}
| 2,422 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/data/services/impl/jpa
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/data/services/impl/jpa/entities/ClusterEntityTest.java
|
/*
*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.data.services.impl.jpa.entities;
import com.google.common.collect.Sets;
import com.netflix.genie.common.internal.dtos.ClusterStatus;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import javax.validation.ConstraintViolationException;
import java.util.Set;
/**
* Test the Cluster class.
*
* @author tgianos
*/
class ClusterEntityTest extends EntityTestBase {
private static final String NAME = "h2prod";
private static final String USER = "tgianos";
private static final String CONFIG = "s3://netflix/clusters/configs/config1";
private static final String VERSION = "1.2.3";
private ClusterEntity c;
private Set<FileEntity> configs;
@BeforeEach
void setup() {
this.c = new ClusterEntity();
final FileEntity config = new FileEntity();
config.setFile(CONFIG);
this.configs = Sets.newHashSet(config);
this.c.setName(NAME);
this.c.setUser(USER);
this.c.setVersion(VERSION);
this.c.setStatus(ClusterStatus.UP.name());
}
@Test
void testDefaultConstructor() {
final ClusterEntity entity = new ClusterEntity();
Assertions.assertThat(entity.getName()).isNull();
Assertions.assertThat(entity.getStatus()).isNull();
Assertions.assertThat(entity.getUser()).isNull();
Assertions.assertThat(entity.getVersion()).isNull();
Assertions.assertThat(entity.getConfigs()).isEmpty();
Assertions.assertThat(entity.getDependencies()).isEmpty();
Assertions.assertThat(entity.getTags()).isEmpty();
}
@Test
void testValidate() {
this.validate(this.c);
}
@Test
void testValidateNoName() {
this.c.setName("");
Assertions
.assertThatExceptionOfType(ConstraintViolationException.class)
.isThrownBy(() -> this.validate(this.c));
}
@Test
void testValidateNoUser() {
this.c.setUser(" ");
Assertions
.assertThatExceptionOfType(ConstraintViolationException.class)
.isThrownBy(() -> this.validate(this.c));
}
@Test
void testValidateNoVersion() {
this.c.setVersion("\t");
Assertions
.assertThatExceptionOfType(ConstraintViolationException.class)
.isThrownBy(() -> this.validate(this.c));
}
@Test
void testSetStatus() {
this.c.setStatus(ClusterStatus.TERMINATED.name());
Assertions.assertThat(this.c.getStatus()).isEqualTo(ClusterStatus.TERMINATED.name());
}
@Test
void testSetTags() {
Assertions.assertThat(this.c.getTags()).isEmpty();
final TagEntity prodTag = new TagEntity();
prodTag.setTag("prod");
final TagEntity slaTag = new TagEntity();
slaTag.setTag("sla");
final Set<TagEntity> tags = Sets.newHashSet(prodTag, slaTag);
this.c.setTags(tags);
Assertions.assertThat(this.c.getTags()).isEqualTo(tags);
this.c.setTags(null);
Assertions.assertThat(this.c.getTags()).isEmpty();
}
@Test
void testSetConfigs() {
Assertions.assertThat(this.c.getConfigs()).isEmpty();
this.c.setConfigs(this.configs);
Assertions.assertThat(this.c.getConfigs()).isEqualTo(this.configs);
this.c.setConfigs(null);
Assertions.assertThat(c.getConfigs()).isEmpty();
}
@Test
void testSetDependencies() {
Assertions.assertThat(this.c.getDependencies()).isEmpty();
final FileEntity dependency = new FileEntity();
dependency.setFile("s3://netflix/jars/myJar.jar");
final Set<FileEntity> dependencies = Sets.newHashSet(dependency);
this.c.setDependencies(dependencies);
Assertions.assertThat(this.c.getDependencies()).isEqualTo(dependencies);
this.c.setDependencies(null);
Assertions.assertThat(this.c.getDependencies()).isEmpty();
}
@Test
void canSetClusterTags() {
final TagEntity oneTag = new TagEntity();
oneTag.setTag("one");
final TagEntity twoTag = new TagEntity();
twoTag.setTag("tow");
final TagEntity preTag = new TagEntity();
preTag.setTag("Pre");
final Set<TagEntity> tags = Sets.newHashSet(oneTag, twoTag, preTag);
this.c.setTags(tags);
Assertions.assertThat(this.c.getTags()).isEqualTo(tags);
this.c.setTags(Sets.newHashSet());
Assertions.assertThat(this.c.getTags()).isEmpty();
this.c.setTags(null);
Assertions.assertThat(this.c.getTags()).isEmpty();
}
@Test
void testToString() {
Assertions.assertThat(this.c.toString()).isNotBlank();
}
}
| 2,423 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/data/services/impl/jpa
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/data/services/impl/jpa/entities/TagEntityTest.java
|
/*
*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.data.services.impl.jpa.entities;
import org.apache.commons.lang3.StringUtils;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import javax.validation.ConstraintViolationException;
import java.util.UUID;
/**
* Unit tests for the TagEntity class.
*
* @author tgianos
* @since 3.3.0
*/
class TagEntityTest extends EntityTestBase {
/**
* Make sure the argument constructor sets the tag argument.
*/
@Test
void canCreateTagEntityWithTag() {
final String tag = UUID.randomUUID().toString();
final TagEntity tagEntity = new TagEntity(tag);
Assertions.assertThat(tagEntity.getTag()).isEqualTo(tag);
}
/**
* Make sure we can create a tag.
*/
@Test
void canCreateTagEntity() {
final TagEntity tagEntity = new TagEntity();
final String tag = UUID.randomUUID().toString();
tagEntity.setTag(tag);
Assertions.assertThat(tagEntity.getTag()).isEqualTo(tag);
}
/**
* Make sure a tag can't be validated if it exceeds size limitations.
*/
@Test
void cantCreateTagEntityDueToSize() {
final TagEntity tagEntity = new TagEntity();
final String tag = StringUtils.rightPad(UUID.randomUUID().toString(), 256);
tagEntity.setTag(tag);
Assertions
.assertThatExceptionOfType(ConstraintViolationException.class)
.isThrownBy(() -> this.validate(tagEntity));
}
/**
* Make sure a tag can't be validated if the value is blank.
*/
@Test
void cantCreateTagEntityDueToNoTag() {
final TagEntity tagEntity = new TagEntity();
final String tag = "";
tagEntity.setTag(tag);
Assertions
.assertThatExceptionOfType(ConstraintViolationException.class)
.isThrownBy(() -> this.validate(tagEntity));
}
/**
* Test to make sure equals and hash code only care about the unique tag.
*/
@Test
void testEqualsAndHashCode() {
final String tag = UUID.randomUUID().toString();
final TagEntity one = new TagEntity(tag);
final TagEntity two = new TagEntity(tag);
final TagEntity three = new TagEntity(UUID.randomUUID().toString());
Assertions.assertThat(one).isEqualTo(two);
Assertions.assertThat(one).isNotEqualTo(three);
Assertions.assertThat(two).isNotEqualTo(three);
Assertions.assertThat(one.hashCode()).isEqualTo(two.hashCode());
Assertions.assertThat(one.hashCode()).isNotEqualTo(three.hashCode());
Assertions.assertThat(two.hashCode()).isNotEqualTo(three.hashCode());
}
/**
* Test the toString method.
*/
@Test
void testToString() {
Assertions.assertThat(new TagEntity().toString()).isNotBlank();
}
}
| 2,424 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/data/services/impl/jpa
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/data/services/impl/jpa/entities/EntityTestBase.java
|
/*
*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.data.services.impl.jpa.entities;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Optional;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Supplier;
/**
* Base class for all test classes for entities in the model package.
*
* @author tgianos
*/
class EntityTestBase {
private static Validator validator;
/**
* Setup the validator.
*/
@BeforeAll
static void setupClass() {
final ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
validator = factory.getValidator();
}
/**
* Get the validator object.
*
* @param <E> The type of entity to validate
* @param entity The entity to validate
*/
<E> void validate(final E entity) {
final Set<ConstraintViolation<E>> violations = validator.validate(entity);
if (!violations.isEmpty()) {
throw new ConstraintViolationException(violations);
}
}
<T> void testOptionalField(
final Supplier<Optional<T>> getter,
final Consumer<T> setter,
final T testValue
) {
Assertions.assertThat(getter.get()).isNotPresent();
setter.accept(null);
Assertions.assertThat(getter.get()).isNotPresent();
setter.accept(testValue);
Assertions.assertThat(getter.get()).isPresent().contains(testValue);
}
}
| 2,425 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/data/services/impl/jpa
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/data/services/impl/jpa/entities/AuditEntityTest.java
|
/*
*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.data.services.impl.jpa.entities;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import java.time.Instant;
/**
* Tests for the audit entity.
*
* @author tgianos
*/
class AuditEntityTest {
/**
* Test to make sure objects are constructed properly.
*/
@Test
void testConstructor() {
final AuditEntity a = new AuditEntity();
Assertions.assertThat(a.getCreated()).isNotNull();
Assertions.assertThat(a.getUpdated()).isNotNull();
}
/**
* Test to make sure @PrePersist annotation will do what we want before persistence.
*
* @throws InterruptedException If the process is interrupted
*/
@Test
void testOnCreateAuditEntity() throws InterruptedException {
final AuditEntity a = new AuditEntity();
Assertions.assertThat(a.getCreated()).isNotNull();
Assertions.assertThat(a.getUpdated()).isNotNull();
final Instant originalCreated = a.getCreated();
final Instant originalUpdated = a.getUpdated();
Thread.sleep(1);
a.onCreateBaseEntity();
Assertions.assertThat(a.getCreated()).isNotNull();
Assertions.assertThat(a.getUpdated()).isNotNull();
Assertions.assertThat(a.getCreated()).isNotEqualTo(originalCreated);
Assertions.assertThat(a.getUpdated()).isNotEqualTo(originalUpdated);
Assertions.assertThat(a.getCreated()).isEqualTo(a.getUpdated());
}
/**
* Test to make sure the update timestamp is updated by this method.
*
* @throws InterruptedException If the process is interrupted
*/
@Test
void testOnUpdateAuditEntity() throws InterruptedException {
final AuditEntity a = new AuditEntity();
Assertions.assertThat(a.getCreated()).isNotNull();
Assertions.assertThat(a.getUpdated()).isNotNull();
a.onCreateBaseEntity();
final Instant originalCreated = a.getCreated();
final Instant originalUpdated = a.getUpdated();
Thread.sleep(1);
a.onUpdateBaseEntity();
Assertions.assertThat(a.getCreated()).isEqualTo(originalCreated);
Assertions.assertThat(a.getUpdated()).isNotEqualTo(originalUpdated);
}
/**
* Test the toString method.
*/
@Test
void testToString() {
Assertions.assertThat(new AuditEntity().toString()).isNotBlank();
}
}
| 2,426 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/data/services/impl/jpa
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/data/services/impl/jpa/entities/FileEntityTest.java
|
/*
*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.data.services.impl.jpa.entities;
import org.apache.commons.lang3.StringUtils;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import javax.validation.ConstraintViolationException;
import java.util.UUID;
/**
* Unit tests for the FileEntity class.
*
* @author tgianos
* @since 3.3.0
*/
class FileEntityTest extends EntityTestBase {
/**
* Make sure the argument constructor sets the file argument.
*/
@Test
void canCreateFileEntityWithFile() {
final String file = UUID.randomUUID().toString();
final FileEntity fileEntity = new FileEntity(file);
Assertions.assertThat(fileEntity.getFile()).isEqualTo(file);
}
/**
* Make sure we can create a file.
*/
@Test
void canCreateFileEntity() {
final FileEntity fileEntity = new FileEntity();
final String file = UUID.randomUUID().toString();
fileEntity.setFile(file);
Assertions.assertThat(fileEntity.getFile()).isEqualTo(file);
}
/**
* Make sure a file can't be validated if it exceeds size limitations.
*/
@Test
void cantCreateFileEntityDueToSize() {
final FileEntity fileEntity = new FileEntity();
final String file = StringUtils.rightPad(UUID.randomUUID().toString(), 1025);
fileEntity.setFile(file);
Assertions
.assertThatExceptionOfType(ConstraintViolationException.class)
.isThrownBy(() -> this.validate(fileEntity));
}
/**
* Make sure a file can't be validated if the value is blank.
*/
@Test
void cantCreateFileEntityDueToNoFile() {
final FileEntity fileEntity = new FileEntity();
final String file = "";
fileEntity.setFile(file);
Assertions
.assertThatExceptionOfType(ConstraintViolationException.class)
.isThrownBy(() -> this.validate(fileEntity));
}
/**
* Test to make sure equals and hash code only care about the unique file.
*/
@Test
void testEqualsAndHashCode() {
final String file = UUID.randomUUID().toString();
final FileEntity one = new FileEntity();
one.setFile(file);
final FileEntity two = new FileEntity();
two.setFile(file);
final FileEntity three = new FileEntity();
three.setFile(UUID.randomUUID().toString());
Assertions.assertThat(one).isEqualTo(two);
Assertions.assertThat(one).isNotEqualTo(three);
Assertions.assertThat(two).isNotEqualTo(three);
Assertions.assertThat(one.hashCode()).isEqualTo(two.hashCode());
Assertions.assertThat(one.hashCode()).isNotEqualTo(three.hashCode());
Assertions.assertThat(two.hashCode()).isNotEqualTo(three.hashCode());
}
/**
* Test the toString method.
*/
@Test
void testToString() {
Assertions.assertThat(new FileEntity().toString()).isNotBlank();
}
}
| 2,427 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/data/services/impl/jpa
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/data/services/impl/jpa/entities/CommandEntityTest.java
|
/*
*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.data.services.impl.jpa.entities;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.netflix.genie.common.dto.CommandStatus;
import com.netflix.genie.common.internal.exceptions.checked.GenieCheckedException;
import com.netflix.genie.web.exceptions.checked.PreconditionFailedException;
import org.apache.commons.lang3.StringUtils;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import javax.validation.ConstraintViolationException;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.UUID;
/**
* Test the {@link CommandEntity} class.
*
* @author tgianos
*/
class CommandEntityTest extends EntityTestBase {
// Comparators needed because the default equality check for CriterionEntity is to compare the id field
// but that field is set by database code based on insertion and isn't exposed as a setter so substituting
// using the uniqueId field here
private static final Comparator<? super List<? extends CriterionEntity>> UNIQUE_ID_CRITERIA_LIST_COMPARATOR =
(l1, l2) -> {
if (l1.size() != l2.size()) {
return l1.size() - l2.size();
}
for (int i = 0; i < l1.size(); i++) {
final String c1 = l1.get(i).getUniqueId().orElse(UUID.randomUUID().toString());
final String c2 = l2.get(i).getUniqueId().orElse(UUID.randomUUID().toString());
if (!c1.equals(c2)) {
return c1.compareTo(c2);
}
}
return 0;
};
private static final Comparator<CriterionEntity> UNIQUE_ID_CRITERION_COMPARATOR = Comparator.comparing(
criterion -> criterion.getUniqueId().orElse(UUID.randomUUID().toString())
);
private static final String NAME = "pig13";
private static final String USER = "tgianos";
private static final List<String> EXECUTABLE = Lists.newArrayList("/bin/pig13", "-Dblah");
private static final String VERSION = "1.0";
private static final long MEMORY = 10_240L;
private CommandEntity c;
@BeforeEach
void setup() {
this.c = new CommandEntity();
this.c.setName(NAME);
this.c.setUser(USER);
this.c.setVersion(VERSION);
this.c.setStatus(CommandStatus.ACTIVE.name());
this.c.setExecutable(EXECUTABLE);
this.c.setMemory(MEMORY);
}
@Test
void testDefaultConstructor() {
final CommandEntity entity = new CommandEntity();
Assertions.assertThat(entity.getSetupFile()).isNotPresent();
Assertions.assertThat(entity.getExecutable()).isEmpty();
Assertions.assertThat(entity.getName()).isNull();
Assertions.assertThat(entity.getStatus()).isNull();
Assertions.assertThat(entity.getUser()).isNull();
Assertions.assertThat(entity.getVersion()).isNull();
Assertions.assertThat(entity.getConfigs()).isEmpty();
Assertions.assertThat(entity.getDependencies()).isEmpty();
Assertions.assertThat(entity.getTags()).isEmpty();
Assertions.assertThat(entity.getApplications()).isEmpty();
Assertions.assertThat(entity.getMemory()).isNotPresent();
Assertions.assertThat(entity.getLauncherExt()).isNotPresent();
Assertions.assertThat(entity.getImages()).isNotPresent();
}
@Test
void testValidate() {
this.validate(this.c);
}
@Test
void testValidateNoName() {
this.c.setName("");
Assertions
.assertThatExceptionOfType(ConstraintViolationException.class)
.isThrownBy(() -> this.validate(this.c));
}
@Test
void testValidateNoUser() {
this.c.setUser(" ");
Assertions
.assertThatExceptionOfType(ConstraintViolationException.class)
.isThrownBy(() -> this.validate(this.c));
}
@Test
void testValidateNoVersion() {
this.c.setVersion("");
Assertions
.assertThatExceptionOfType(ConstraintViolationException.class)
.isThrownBy(() -> this.validate(this.c));
}
@Test
void testValidateEmptyExecutable() {
this.c.setExecutable(Lists.newArrayList());
Assertions
.assertThatExceptionOfType(ConstraintViolationException.class)
.isThrownBy(() -> this.validate(this.c));
}
@Test
void testValidateBlankExecutable() {
this.c.setExecutable(Lists.newArrayList(" "));
Assertions
.assertThatExceptionOfType(ConstraintViolationException.class)
.isThrownBy(() -> this.validate(this.c));
}
@Test
void testValidateExecutableArgumentTooLong() {
this.c.setExecutable(Lists.newArrayList(StringUtils.leftPad("", 1025, 'e')));
Assertions
.assertThatExceptionOfType(ConstraintViolationException.class)
.isThrownBy(() -> this.validate(this.c));
}
@Test
void testSetStatus() {
this.c.setStatus(CommandStatus.ACTIVE.name());
Assertions.assertThat(this.c.getStatus()).isEqualTo(CommandStatus.ACTIVE.name());
}
@Test
void testSetSetupFile() {
Assertions.assertThat(this.c.getSetupFile()).isNotPresent();
final String setupFile = "s3://netflix.propFile";
final FileEntity setupFileEntity = new FileEntity(setupFile);
this.c.setSetupFile(setupFileEntity);
Assertions.assertThat(this.c.getSetupFile()).isPresent().contains(setupFileEntity);
}
@Test
void testSetExecutable() {
this.c.setExecutable(EXECUTABLE);
Assertions.assertThat(this.c.getExecutable()).isEqualTo(EXECUTABLE);
}
@Test
void testSetMemory() {
Assertions.assertThat(this.c.getMemory()).isPresent().contains(MEMORY);
final long newMemory = MEMORY + 1;
this.c.setMemory(newMemory);
Assertions.assertThat(this.c.getMemory()).isPresent().contains(newMemory);
}
@Test
void testCpu() {
this.testOptionalField(this.c::getCpu, this.c::setCpu, 12);
}
@Test
void testGpu() {
this.testOptionalField(this.c::getGpu, this.c::setGpu, 123);
}
@Test
void testDiskMb() {
this.testOptionalField(this.c::getDiskMb, this.c::setDiskMb, 123_000L);
}
@Test
void testNetworkMbps() {
this.testOptionalField(this.c::getNetworkMbps, this.c::setNetworkMbps, 123_456L);
}
@Test
void testImages() {
this.testOptionalField(
this.c::getImages,
this.c::setImages,
Mockito.mock(JsonNode.class)
);
}
@Test
void testSetConfigs() {
Assertions.assertThat(this.c.getConfigs()).isEmpty();
final Set<FileEntity> configs = Sets.newHashSet(new FileEntity("s3://netflix.configFile"));
this.c.setConfigs(configs);
Assertions.assertThat(this.c.getConfigs()).isEqualTo(configs);
this.c.setConfigs(null);
Assertions.assertThat(this.c.getConfigs()).isEmpty();
}
@Test
void testSetDependencies() {
Assertions.assertThat(this.c.getDependencies()).isEmpty();
final Set<FileEntity> dependencies = Sets.newHashSet(new FileEntity("dep1"));
this.c.setDependencies(dependencies);
Assertions.assertThat(this.c.getDependencies()).isEqualTo(dependencies);
this.c.setDependencies(null);
Assertions.assertThat(this.c.getDependencies()).isEmpty();
}
@Test
void testSetTags() {
Assertions.assertThat(this.c.getTags()).isEmpty();
final TagEntity one = new TagEntity("tag1");
final TagEntity two = new TagEntity("tag2");
final Set<TagEntity> tags = Sets.newHashSet(one, two);
this.c.setTags(tags);
Assertions.assertThat(this.c.getTags()).isEqualTo(tags);
this.c.setTags(null);
Assertions.assertThat(this.c.getTags()).isEmpty();
}
@Test
void testSetApplications() throws GenieCheckedException {
Assertions.assertThat(this.c.getApplications()).isEmpty();
final ApplicationEntity one = new ApplicationEntity();
one.setUniqueId("one");
final ApplicationEntity two = new ApplicationEntity();
two.setUniqueId("two");
final List<ApplicationEntity> applicationEntities = Lists.newArrayList(one, two);
this.c.setApplications(applicationEntities);
Assertions.assertThat(this.c.getApplications()).isEqualTo(applicationEntities);
Assertions.assertThat(one.getCommands()).contains(this.c);
Assertions.assertThat(two.getCommands()).contains(this.c);
applicationEntities.clear();
applicationEntities.add(two);
this.c.setApplications(applicationEntities);
Assertions.assertThat(this.c.getApplications()).isEqualTo(applicationEntities);
Assertions.assertThat(one.getCommands()).doesNotContain(this.c);
Assertions.assertThat(two.getCommands()).contains(this.c);
this.c.setApplications(null);
Assertions.assertThat(this.c.getApplications()).isEmpty();
Assertions.assertThat(one.getCommands()).isEmpty();
Assertions.assertThat(two.getCommands()).isEmpty();
}
@Test
void cantSetApplicationsIfDuplicates() {
final ApplicationEntity one = Mockito.mock(ApplicationEntity.class);
Mockito.when(one.getUniqueId()).thenReturn(UUID.randomUUID().toString());
final ApplicationEntity two = Mockito.mock(ApplicationEntity.class);
Mockito.when(two.getUniqueId()).thenReturn(UUID.randomUUID().toString());
Assertions
.assertThatExceptionOfType(PreconditionFailedException.class)
.isThrownBy(() -> this.c.setApplications(Lists.newArrayList(one, two, one)));
}
@Test
void canAddApplication() throws PreconditionFailedException {
final String id = UUID.randomUUID().toString();
final ApplicationEntity app = new ApplicationEntity();
app.setUniqueId(id);
this.c.addApplication(app);
Assertions.assertThat(this.c.getApplications()).contains(app);
Assertions.assertThat(app.getCommands()).contains(this.c);
}
@Test
void cantAddApplicationThatAlreadyIsInList() throws PreconditionFailedException {
final String id = UUID.randomUUID().toString();
final ApplicationEntity app = new ApplicationEntity();
app.setUniqueId(id);
this.c.addApplication(app);
Assertions
.assertThatExceptionOfType(PreconditionFailedException.class)
.isThrownBy(() -> this.c.addApplication(app));
}
@Test
void canRemoveApplication() throws PreconditionFailedException {
final ApplicationEntity one = new ApplicationEntity();
one.setUniqueId("one");
final ApplicationEntity two = new ApplicationEntity();
two.setUniqueId("two");
Assertions.assertThat(this.c.getApplications()).isEmpty();
this.c.addApplication(one);
Assertions.assertThat(this.c.getApplications()).contains(one);
Assertions.assertThat(this.c.getApplications()).doesNotContain(two);
Assertions.assertThat(one.getCommands()).contains(this.c);
Assertions.assertThat(two.getCommands()).isEmpty();
this.c.addApplication(two);
Assertions.assertThat(this.c.getApplications()).contains(one);
Assertions.assertThat(this.c.getApplications()).contains(two);
Assertions.assertThat(one.getCommands()).contains(this.c);
Assertions.assertThat(two.getCommands()).contains(this.c);
this.c.removeApplication(one);
Assertions.assertThat(this.c.getApplications()).doesNotContain(one);
Assertions.assertThat(this.c.getApplications()).contains(two);
Assertions.assertThat(one.getCommands()).doesNotContain(this.c);
Assertions.assertThat(two.getCommands()).contains(this.c);
}
@Test
void testToString() {
Assertions.assertThat(this.c.toString()).isNotBlank();
}
@Test
void canManipulateClusterCriteria() {
Assertions.assertThat(this.c.getClusterCriteria()).isEmpty();
final CriterionEntity criterion0 = this.createTestCriterion();
final CriterionEntity criterion1 = this.createTestCriterion();
final CriterionEntity criterion2 = this.createTestCriterion();
final CriterionEntity criterion3 = this.createTestCriterion();
final CriterionEntity criterion4 = this.createTestCriterion();
final CriterionEntity criterion5 = this.createTestCriterion();
final CriterionEntity criterion6 = this.createTestCriterion();
final CriterionEntity criterion7 = this.createTestCriterion();
final CriterionEntity criterion8 = this.createTestCriterion();
final List<CriterionEntity> clusterCriteria = Lists.newArrayList(criterion0, criterion1, criterion2);
this.c.setClusterCriteria(clusterCriteria);
Assertions
.assertThat(this.c.getClusterCriteria())
.usingComparator(UNIQUE_ID_CRITERIA_LIST_COMPARATOR)
.isEqualTo(clusterCriteria);
this.c.setClusterCriteria(null);
Assertions.assertThat(this.c.getClusterCriteria()).isEmpty();
this.c.setClusterCriteria(clusterCriteria);
Assertions
.assertThat(this.c.getClusterCriteria())
.usingComparator(UNIQUE_ID_CRITERIA_LIST_COMPARATOR)
.isEqualTo(clusterCriteria);
this.c.setClusterCriteria(Lists.newArrayList());
Assertions.assertThat(this.c.getClusterCriteria()).isEmpty();
this.c.setClusterCriteria(clusterCriteria);
Assertions
.assertThat(this.c.getClusterCriteria())
.usingComparator(UNIQUE_ID_CRITERIA_LIST_COMPARATOR)
.isEqualTo(clusterCriteria);
this.c.addClusterCriterion(criterion3);
Assertions
.assertThat(this.c.getClusterCriteria())
.size()
.isEqualTo(4)
.returnToIterable()
.element(3)
.usingComparator(UNIQUE_ID_CRITERION_COMPARATOR)
.isEqualTo(criterion3);
this.c.addClusterCriterion(criterion4, this.c.getClusterCriteria().size());
Assertions
.assertThat(this.c.getClusterCriteria())
.size()
.isEqualTo(5)
.returnToIterable()
.element(4)
.usingComparator(UNIQUE_ID_CRITERION_COMPARATOR)
.isEqualTo(criterion4);
this.c.addClusterCriterion(criterion5, this.c.getClusterCriteria().size() + 80);
Assertions
.assertThat(this.c.getClusterCriteria())
.size()
.isEqualTo(6)
.returnToIterable()
.element(5)
.usingComparator(UNIQUE_ID_CRITERION_COMPARATOR)
.isEqualTo(criterion5);
this.c.addClusterCriterion(criterion6, -5000);
Assertions
.assertThat(this.c.getClusterCriteria())
.size()
.isEqualTo(7)
.returnToIterable()
.element(0)
.usingComparator(UNIQUE_ID_CRITERION_COMPARATOR)
.isEqualTo(criterion6);
this.c.addClusterCriterion(criterion7, 0);
Assertions
.assertThat(this.c.getClusterCriteria())
.size()
.isEqualTo(8)
.returnToIterable()
.element(0)
.usingComparator(UNIQUE_ID_CRITERION_COMPARATOR)
.isEqualTo(criterion7);
this.c.addClusterCriterion(criterion8, 1);
Assertions
.assertThat(this.c.getClusterCriteria())
.size()
.isEqualTo(9)
.returnToIterable()
.element(1)
.usingComparator(UNIQUE_ID_CRITERION_COMPARATOR)
.isEqualTo(criterion8);
Assertions
.assertThatIllegalArgumentException()
.isThrownBy(() -> this.c.removeClusterCriterion(-1));
Assertions
.assertThatIllegalArgumentException()
.isThrownBy(() -> this.c.removeClusterCriterion(this.c.getClusterCriteria().size()));
Assertions
.assertThat(this.c.removeClusterCriterion(0))
.usingComparator(UNIQUE_ID_CRITERION_COMPARATOR)
.isEqualTo(criterion7);
Assertions
.assertThat(this.c.removeClusterCriterion(0))
.usingComparator(UNIQUE_ID_CRITERION_COMPARATOR)
.isEqualTo(criterion8);
Assertions
.assertThat(this.c.removeClusterCriterion(0))
.usingComparator(UNIQUE_ID_CRITERION_COMPARATOR)
.isEqualTo(criterion6);
Assertions
.assertThat(this.c.removeClusterCriterion(3))
.usingComparator(UNIQUE_ID_CRITERION_COMPARATOR)
.isEqualTo(criterion3);
Assertions
.assertThat(this.c.removeClusterCriterion(4))
.usingComparator(UNIQUE_ID_CRITERION_COMPARATOR)
.isEqualTo(criterion5);
Assertions
.assertThat(this.c.removeClusterCriterion(3))
.usingComparator(UNIQUE_ID_CRITERION_COMPARATOR)
.isEqualTo(criterion4);
Assertions
.assertThat(this.c.getClusterCriteria())
.usingComparator(UNIQUE_ID_CRITERIA_LIST_COMPARATOR)
.usingComparator(UNIQUE_ID_CRITERIA_LIST_COMPARATOR)
.isEqualTo(clusterCriteria);
}
@Test
void canSetLauncherExt() {
Assertions.assertThat(this.c.getLauncherExt()).isNotPresent();
final JsonNode launcherMetadata = Mockito.mock(JsonNode.class);
this.c.setLauncherExt(launcherMetadata);
Assertions.assertThat(this.c.getLauncherExt()).isPresent().contains(launcherMetadata);
}
private CriterionEntity createTestCriterion() {
final CriterionEntity criterion = new CriterionEntity();
criterion.setUniqueId(UUID.randomUUID().toString());
return criterion;
}
}
| 2,428 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/data/services/impl/jpa
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/data/services/impl/jpa/entities/package-info.java
|
/*
*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Classes that test the Genie entity classes.
*
* @author tgianos
*/
package com.netflix.genie.web.data.services.impl.jpa.entities;
| 2,429 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/data/services/impl/jpa
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/data/services/impl/jpa/entities/IdEntityTest.java
|
/*
*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.data.services.impl.jpa.entities;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
/**
* Unit tests for the IdEntity class.
*
* @author tgianos
* @since 3.3.0
*/
class IdEntityTest {
/**
* Test the toString method.
*/
@Test
void testToString() {
Assertions.assertThat(new IdEntity().toString()).isNotBlank();
}
}
| 2,430 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/data/services/impl/jpa
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/data/services/impl/jpa/entities/BaseEntityTest.java
|
/*
*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.data.services.impl.jpa.entities;
import com.fasterxml.jackson.databind.JsonNode;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import javax.validation.ConstraintViolationException;
import java.util.UUID;
/**
* Test the BaseEntity class and methods.
*
* @author tgianos
*/
class BaseEntityTest extends EntityTestBase {
private static final String UNIQUE_ID = UUID.randomUUID().toString();
private static final String NAME = "pig13";
private static final String USER = "tgianos";
private static final String VERSION = "1.0";
private static final JsonNode METADATA = Mockito.mock(JsonNode.class);
private BaseEntity b;
/**
* Setup the tests.
*/
@BeforeEach
void setup() {
this.b = new BaseEntity();
this.b.setUniqueId(UNIQUE_ID);
this.b.setName(NAME);
this.b.setUser(USER);
this.b.setVersion(VERSION);
}
/**
* Test the default Constructor.
*/
@Test
void testDefaultConstructor() {
final BaseEntity local = new BaseEntity();
Assertions.assertThat(local.getUniqueId()).isNotBlank();
Assertions.assertThat(local.getName()).isNull();
Assertions.assertThat(local.getUser()).isNull();
Assertions.assertThat(local.getVersion()).isNull();
Assertions.assertThat(local.getDescription()).isNotPresent();
Assertions.assertThat(local.getSetupFile()).isNotPresent();
Assertions.assertThat(local.isRequestedId()).isFalse();
}
/**
* Test to make sure validation works.
*/
@Test
void testValidate() {
this.validate(this.b);
}
/**
* Test to make sure validation works.
*/
@Test
void testValidateWithNothing() {
Assertions
.assertThatExceptionOfType(ConstraintViolationException.class)
.isThrownBy(() -> this.validate(new BaseEntity()));
}
/**
* Test to make sure validation works and throws exception when no name entered.
*/
@Test
void testValidateNoName() {
this.b.setName("");
Assertions
.assertThatExceptionOfType(ConstraintViolationException.class)
.isThrownBy(() -> this.validate(this.b));
}
/**
* Test to make sure validation works and throws exception when no name entered.
*/
@Test
void testValidateNoUser() {
this.b.setUser(" ");
Assertions
.assertThatExceptionOfType(ConstraintViolationException.class)
.isThrownBy(() -> this.validate(this.b));
}
/**
* Test to make sure validation works and throws exception when no name entered.
*/
@Test
void testValidateNoVersion() {
this.b.setVersion("");
Assertions
.assertThatExceptionOfType(ConstraintViolationException.class)
.isThrownBy(() -> this.validate(this.b));
}
/**
* Test the getting and setting of the unique id.
*/
@Test
void testSetUniqueId() {
final BaseEntity local = new BaseEntity();
Assertions.assertThat(local.getUniqueId()).isNotBlank();
Assertions.assertThat(local.getUniqueId()).isNotEqualTo(UNIQUE_ID);
local.setUniqueId(UNIQUE_ID);
Assertions.assertThat(local.getUniqueId()).isEqualTo(UNIQUE_ID);
}
/**
* Test to make sure the name is being set properly.
*/
@Test
void testSetName() {
final BaseEntity local = new BaseEntity();
Assertions.assertThat(local.getName()).isNull();
local.setName(NAME);
Assertions.assertThat(local.getName()).isEqualTo(NAME);
}
/**
* Test to make sure the user is being set properly.
*/
@Test
void testSetUser() {
final BaseEntity local = new BaseEntity();
Assertions.assertThat(local.getUser()).isNull();
local.setUser(USER);
Assertions.assertThat(local.getUser()).isEqualTo(USER);
}
/**
* Test to make sure the version is being set properly.
*/
@Test
void testSetVersion() {
final BaseEntity local = new BaseEntity();
Assertions.assertThat(local.getVersion()).isNull();
local.setVersion(VERSION);
Assertions.assertThat(local.getVersion()).isEqualTo(VERSION);
}
/**
* Test the description get/set.
*/
@Test
void testSetDescription() {
Assertions.assertThat(this.b.getDescription()).isNotPresent();
final String description = "Test description";
this.b.setDescription(description);
Assertions.assertThat(this.b.getDescription()).isPresent().contains(description);
}
/**
* Test the setup file get/set.
*/
@Test
void testSetSetupFile() {
Assertions.assertThat(this.b.getSetupFile()).isNotPresent();
final FileEntity setupFile = new FileEntity(UUID.randomUUID().toString());
this.b.setSetupFile(setupFile);
Assertions.assertThat(this.b.getSetupFile()).isPresent().contains(setupFile);
this.b.setSetupFile(null);
Assertions.assertThat(this.b.getSetupFile()).isNotPresent();
}
/**
* Test the metadata setter and getter.
*/
@Test
void testSetMetadata() {
Assertions.assertThat(this.b.getMetadata()).isNotPresent();
this.b.setMetadata(METADATA);
Assertions.assertThat(this.b.getMetadata()).isPresent().contains(METADATA);
this.b.setMetadata(null);
Assertions.assertThat(this.b.getMetadata()).isNotPresent();
}
/**
* Test the is requested id fields.
*/
@Test
void testSetRequestedId() {
Assertions.assertThat(this.b.isRequestedId()).isFalse();
this.b.setRequestedId(true);
Assertions.assertThat(this.b.isRequestedId()).isTrue();
}
/**
* Test to make sure equals and hash code only care about the unique id.
*/
@Test
void testEqualsAndHashCode() {
final String id = UUID.randomUUID().toString();
final String name = UUID.randomUUID().toString();
final BaseEntity one = new BaseEntity();
one.setUniqueId(id);
one.setName(UUID.randomUUID().toString());
final BaseEntity two = new BaseEntity();
two.setUniqueId(id);
two.setName(name);
final BaseEntity three = new BaseEntity();
three.setUniqueId(UUID.randomUUID().toString());
three.setName(name);
Assertions.assertThat(one).isEqualTo(two);
Assertions.assertThat(one).isNotEqualTo(three);
Assertions.assertThat(two).isNotEqualTo(three);
Assertions.assertThat(one.hashCode()).isEqualTo(two.hashCode());
Assertions.assertThat(one.hashCode()).isNotEqualTo(three.hashCode());
Assertions.assertThat(two.hashCode()).isNotEqualTo(three.hashCode());
}
/**
* Test the toString method.
*/
@Test
void testToString() {
Assertions.assertThat(this.b.toString()).isNotBlank();
}
}
| 2,431 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/processors/package-info.java
|
/*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Tests for processors.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.spring.processors;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,432 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/processors/GenieDefaultPropertiesPostProcessorTest.java
|
/*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.spring.processors;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;
/**
* Tests to make sure default properties are loaded when {@link GenieDefaultPropertiesPostProcessor} is applied.
*
* @author tgianos
* @since 4.0.0
*/
class GenieDefaultPropertiesPostProcessorTest {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner();
private final GenieDefaultPropertiesPostProcessor processor = new GenieDefaultPropertiesPostProcessor();
/**
* Test to make sure the smoke property is in the environment after the post processor is invoked.
*/
@Test
void testSmokeProperty() {
this.contextRunner
.run(
context -> {
final SpringApplication application = Mockito.mock(SpringApplication.class);
final ConfigurableEnvironment environment = context.getEnvironment();
Assertions.assertThat(
environment
.getPropertySources()
.contains(GenieDefaultPropertiesPostProcessor.DEFAULT_PROPERTY_SOURCE_NAME)
).isFalse();
Assertions.assertThat(
environment
.getPropertySources()
.contains(GenieDefaultPropertiesPostProcessor.DEFAULT_PROD_PROPERTY_SOURCE_NAME)
).isFalse();
Assertions.assertThat(environment.getProperty("genie.smoke")).isNull();
this.processor.postProcessEnvironment(environment, application);
Assertions.assertThat(
environment
.getPropertySources()
.contains(GenieDefaultPropertiesPostProcessor.DEFAULT_PROPERTY_SOURCE_NAME)
).isTrue();
Assertions.assertThat(
environment
.getPropertySources()
.contains(GenieDefaultPropertiesPostProcessor.DEFAULT_PROD_PROPERTY_SOURCE_NAME)
).isFalse();
Assertions
.assertThat(environment.getProperty("genie.smoke", Boolean.class, false))
.isTrue();
}
);
}
/**
* Test to make sure the prod smoke property is in the environment after the post processor is invoked.
*/
@Test
void testProdSmokeProperty() {
this.contextRunner
.withPropertyValues("spring.profiles.active=prod")
.run(
context -> {
final SpringApplication application = Mockito.mock(SpringApplication.class);
final ConfigurableEnvironment environment = context.getEnvironment();
final MutablePropertySources propertySources = environment.getPropertySources();
Assertions.assertThat(
propertySources.contains(GenieDefaultPropertiesPostProcessor.DEFAULT_PROPERTY_SOURCE_NAME)
).isFalse();
Assertions.assertThat(
propertySources.contains(GenieDefaultPropertiesPostProcessor.DEFAULT_PROD_PROPERTY_SOURCE_NAME)
).isFalse();
Assertions.assertThat(environment.getProperty("genie.smoke")).isNull();
this.processor.postProcessEnvironment(environment, application);
Assertions.assertThat(
propertySources.contains(GenieDefaultPropertiesPostProcessor.DEFAULT_PROPERTY_SOURCE_NAME)
).isTrue();
Assertions.assertThat(
propertySources.contains(GenieDefaultPropertiesPostProcessor.DEFAULT_PROD_PROPERTY_SOURCE_NAME)
).isTrue();
final PropertySource<?> defaultPropertySource
= propertySources.get(GenieDefaultPropertiesPostProcessor.DEFAULT_PROPERTY_SOURCE_NAME);
final PropertySource<?> defaultProdPropertySource
= propertySources.get(GenieDefaultPropertiesPostProcessor.DEFAULT_PROD_PROPERTY_SOURCE_NAME);
Assertions.assertThat(defaultPropertySource).isNotNull();
Assertions.assertThat(defaultProdPropertySource).isNotNull();
// Lower value = higher precedence. Kind of confusing. had to look at source.
Assertions
.assertThat(propertySources.precedenceOf(defaultProdPropertySource))
.isLessThan(propertySources.precedenceOf(defaultPropertySource));
Assertions
.assertThat(environment.getProperty("genie.smoke", Boolean.class, true))
.isFalse();
}
);
}
}
| 2,433 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/ValidationAutoConfigurationTest.java
|
/*
*
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.spring.autoconfigure;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;
import javax.validation.Validator;
/**
* Tests for the bean validation configuration.
*
* @author tgianos
* @since 3.0.0
*/
public class ValidationAutoConfigurationTest {
private ApplicationContextRunner contextRunner =
new ApplicationContextRunner()
.withConfiguration(
AutoConfigurations.of(
ValidationAutoConfiguration.class
)
);
/**
* The auto configuration creates the expected beans.
*/
@Test
public void expectedBeansExist() {
this.contextRunner.run(
context -> {
Assertions.assertThat(context).hasSingleBean(MethodValidationPostProcessor.class);
Assertions.assertThat(context).hasSingleBean(Validator.class);
Assertions.assertThat(context).hasSingleBean(LocalValidatorFactoryBean.class);
}
);
}
}
| 2,434 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/CachingAutoConfigurationTest.java
|
/*
*
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.spring.autoconfigure;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.cache.CacheManager;
import org.springframework.cache.caffeine.CaffeineCacheManager;
/**
* Tests for {@link CachingAutoConfiguration}.
*
* @author tgianos
* @since 4.0.0
*/
class CachingAutoConfigurationTest {
private ApplicationContextRunner contextRunner =
new ApplicationContextRunner()
.withConfiguration(
AutoConfigurations.of(
CacheAutoConfiguration.class,
CachingAutoConfiguration.class
)
);
/**
* The auto configuration creates the expected beans.
*/
@Test
void expectedBeansExist() {
this.contextRunner.run(
context -> {
// This should be provided by the Spring Boot starter after @EnableCaching is applied
Assertions.assertThat(context).hasSingleBean(CacheManager.class);
Assertions.assertThat(context).hasSingleBean(CaffeineCacheManager.class);
}
);
}
}
| 2,435 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/ZookeeperAutoConfigurationTest.java
|
/*
*
* Copyright 2020 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.spring.autoconfigure;
import com.netflix.genie.web.properties.ZookeeperProperties;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.listen.Listenable;
import org.apache.curator.x.discovery.ServiceDiscovery;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.zookeeper.config.LeaderInitiatorFactoryBean;
/**
* Unit tests for the {@link ZookeeperAutoConfiguration} class.
*
* @author mprimi
* @since 4.0.0
*/
class ZookeeperAutoConfigurationTest {
private ApplicationContextRunner contextRunner =
new ApplicationContextRunner()
.withConfiguration(
AutoConfigurations.of(
ZookeeperAutoConfiguration.class
)
);
/**
* Test expected beans when Zookeeper is not enabled.
*/
@Test
void expectedBeansWithZookeeperDisabled() {
this.contextRunner.run(
context -> {
Assertions.assertThat(context).doesNotHaveBean(ZookeeperProperties.class);
Assertions.assertThat(context).doesNotHaveBean(LeaderInitiatorFactoryBean.class);
Assertions.assertThat(context).doesNotHaveBean(ServiceDiscovery.class);
Assertions.assertThat(context).doesNotHaveBean(Listenable.class);
}
);
}
/**
* Test expected beans when Zookeeper is enabled.
*/
@Test
void expectedBeansWithZookeeperEnabled() {
this.contextRunner
.withUserConfiguration(ZookeeperMockConfig.class)
.run(
context -> {
Assertions.assertThat(context).hasSingleBean(ZookeeperProperties.class);
Assertions.assertThat(context).hasSingleBean(LeaderInitiatorFactoryBean.class);
Assertions.assertThat(context).hasSingleBean(ServiceDiscovery.class);
Assertions.assertThat(context).hasSingleBean(Listenable.class);
}
);
}
/**
* Mock configuration for pretending zookeeper is enabled.
*/
@Configuration
static class ZookeeperMockConfig {
/**
* Mocked bean.
*
* @return Mocked bean instance.
*/
@Bean
@SuppressWarnings("unchecked")
CuratorFramework curatorFramework() {
final CuratorFramework curatorFramework = Mockito.mock(CuratorFramework.class);
Mockito
.when(curatorFramework.getConnectionStateListenable())
.thenReturn(Mockito.mock(Listenable.class));
return curatorFramework;
}
}
}
| 2,436 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/RetryAutoConfigurationTest.java
|
/*
*
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.spring.autoconfigure;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.retry.annotation.RetryConfiguration;
/**
* Tests for {@link RetryAutoConfiguration}.
*
* @author tgianos
* @since 4.0.0
*/
class RetryAutoConfigurationTest {
private ApplicationContextRunner contextRunner =
new ApplicationContextRunner()
.withConfiguration(
AutoConfigurations.of(
RetryAutoConfiguration.class
)
);
/**
* The auto configuration creates the expected beans.
*/
@Test
void expectedBeansExist() {
this.contextRunner.run(
context -> {
// This configuration should be imported by the @EnableRetry annotation
Assertions.assertThat(context).hasSingleBean(RetryConfiguration.class);
}
);
}
}
| 2,437 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/package-info.java
|
/*
*
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Tests for config classes.
*
* @author tgianos
* @since 3.0.0
*/
package com.netflix.genie.web.spring.autoconfigure;
| 2,438 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/tasks/TasksAutoConfigurationTest.java
|
/*
*
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.spring.autoconfigure.tasks;
import com.netflix.genie.web.properties.TasksExecutorPoolProperties;
import com.netflix.genie.web.properties.TasksSchedulerPoolProperties;
import org.apache.commons.exec.Executor;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
/**
* Unit tests for {@link TasksAutoConfiguration} class.
*
* @author tgianos
* @since 3.0.0
*/
class TasksAutoConfigurationTest {
private ApplicationContextRunner contextRunner =
new ApplicationContextRunner()
.withConfiguration(
AutoConfigurations.of(
TasksAutoConfiguration.class
)
);
/**
* All the expected beans exist.
*/
@Test
void expectedBeansExist() {
this.contextRunner.run(
context -> {
Assertions.assertThat(context).hasSingleBean(TasksExecutorPoolProperties.class);
Assertions.assertThat(context).hasSingleBean(TasksSchedulerPoolProperties.class);
Assertions.assertThat(context).hasSingleBean(Executor.class);
Assertions.assertThat(context).hasBean("genieTaskScheduler");
Assertions.assertThat(context).hasBean("genieAsyncTaskExecutor");
Assertions.assertThat(context).hasBean("genieSyncTaskExecutor");
}
);
}
}
| 2,439 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/tasks/package-info.java
|
/*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Tests for this package.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.spring.autoconfigure.tasks;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,440 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/tasks
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/tasks/leader/LeaderAutoConfigurationTest.java
|
/*
*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.spring.autoconfigure.tasks.leader;
import com.netflix.genie.common.internal.util.GenieHostInfo;
import com.netflix.genie.web.agent.services.AgentRoutingService;
import com.netflix.genie.web.data.services.DataServices;
import com.netflix.genie.web.data.services.PersistenceService;
import com.netflix.genie.web.events.GenieEventBus;
import com.netflix.genie.web.properties.AgentCleanupProperties;
import com.netflix.genie.web.properties.ArchiveStatusCleanupProperties;
import com.netflix.genie.web.properties.DatabaseCleanupProperties;
import com.netflix.genie.web.properties.JobsProperties;
import com.netflix.genie.web.properties.LeadershipProperties;
import com.netflix.genie.web.properties.UserMetricsProperties;
import com.netflix.genie.web.services.ClusterLeaderService;
import com.netflix.genie.web.spring.actuators.LeaderElectionActuator;
import com.netflix.genie.web.spring.autoconfigure.tasks.TasksAutoConfiguration;
import com.netflix.genie.web.tasks.leader.AgentJobCleanupTask;
import com.netflix.genie.web.tasks.leader.ArchiveStatusCleanupTask;
import com.netflix.genie.web.tasks.leader.DatabaseCleanupTask;
import com.netflix.genie.web.tasks.leader.LeaderTasksCoordinator;
import com.netflix.genie.web.tasks.leader.LocalLeader;
import com.netflix.genie.web.tasks.leader.UserMetricsTask;
import io.micrometer.core.instrument.MeterRegistry;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.zookeeper.leader.LeaderInitiator;
import org.springframework.web.client.RestTemplate;
/**
* Unit tests for the {@link LeaderAutoConfiguration} class.
*
* @author tgianos
* @since 3.1.0
*/
class LeaderAutoConfigurationTest {
private ApplicationContextRunner contextRunner =
new ApplicationContextRunner()
.withConfiguration(
AutoConfigurations.of(
TasksAutoConfiguration.class,
LeaderAutoConfiguration.class
)
)
.withUserConfiguration(MockBeanConfig.class);
/**
* All the expected default beans exist.
*/
@Test
void expectedBeansExist() {
this.contextRunner.run(
context -> {
Assertions.assertThat(context).hasSingleBean(AgentCleanupProperties.class);
Assertions.assertThat(context).hasSingleBean(ArchiveStatusCleanupProperties.class);
Assertions.assertThat(context).hasSingleBean(DatabaseCleanupProperties.class);
Assertions.assertThat(context).hasSingleBean(LeadershipProperties.class);
Assertions.assertThat(context).hasSingleBean(UserMetricsProperties.class);
Assertions.assertThat(context).hasSingleBean(LeaderTasksCoordinator.class);
Assertions.assertThat(context).hasSingleBean(LocalLeader.class);
Assertions.assertThat(context).hasSingleBean(ClusterLeaderService.class);
Assertions.assertThat(context).hasSingleBean(LeaderElectionActuator.class);
// Optional beans
Assertions.assertThat(context).doesNotHaveBean(DatabaseCleanupTask.class);
Assertions.assertThat(context).doesNotHaveBean(UserMetricsTask.class);
Assertions.assertThat(context).doesNotHaveBean(AgentJobCleanupTask.class);
Assertions.assertThat(context).doesNotHaveBean(ArchiveStatusCleanupTask.class);
}
);
}
/**
* All the expected optional beans exist.
*/
@Test
void optionalBeansCreated() {
this.contextRunner
.withPropertyValues(
"genie.tasks.database-cleanup.enabled=true",
"genie.tasks.user-metrics.enabled=true",
"genie.tasks.agent-cleanup.enabled=true",
"genie.tasks.archive-status-cleanup.enabled=true"
)
.run(
context -> {
Assertions.assertThat(context).hasSingleBean(AgentCleanupProperties.class);
Assertions.assertThat(context).hasSingleBean(ArchiveStatusCleanupProperties.class);
Assertions.assertThat(context).hasSingleBean(DatabaseCleanupProperties.class);
Assertions.assertThat(context).hasSingleBean(LeadershipProperties.class);
Assertions.assertThat(context).hasSingleBean(UserMetricsProperties.class);
Assertions.assertThat(context).hasSingleBean(LeaderTasksCoordinator.class);
Assertions.assertThat(context).hasSingleBean(LocalLeader.class);
Assertions.assertThat(context).hasSingleBean(ClusterLeaderService.class);
Assertions.assertThat(context).hasSingleBean(LeaderElectionActuator.class);
// Optional beans
Assertions.assertThat(context).hasSingleBean(DatabaseCleanupTask.class);
Assertions.assertThat(context).hasSingleBean(UserMetricsTask.class);
Assertions.assertThat(context).hasSingleBean(AgentJobCleanupTask.class);
Assertions.assertThat(context).hasSingleBean(ArchiveStatusCleanupTask.class);
}
);
}
/**
* All the expected beans exist when zookeeper is enabled.
*/
@Test
void expectedZookeeperBeansExist() {
this.contextRunner
.withUserConfiguration(ZookeeperMockConfig.class)
.run(
context -> {
Assertions.assertThat(context).hasSingleBean(AgentCleanupProperties.class);
Assertions.assertThat(context).hasSingleBean(DatabaseCleanupProperties.class);
Assertions.assertThat(context).hasSingleBean(LeadershipProperties.class);
Assertions.assertThat(context).hasSingleBean(UserMetricsProperties.class);
Assertions.assertThat(context).hasSingleBean(LeaderTasksCoordinator.class);
Assertions.assertThat(context).doesNotHaveBean(LocalLeader.class);
Assertions.assertThat(context).hasSingleBean(ClusterLeaderService.class);
Assertions.assertThat(context).hasSingleBean(LeaderElectionActuator.class);
// Optional beans
Assertions.assertThat(context).doesNotHaveBean(DatabaseCleanupTask.class);
Assertions.assertThat(context).doesNotHaveBean(UserMetricsTask.class);
Assertions.assertThat(context).doesNotHaveBean(AgentJobCleanupTask.class);
}
);
}
static class MockBeanConfig {
@Bean
GenieHostInfo genieHostInfo() {
return Mockito.mock(GenieHostInfo.class);
}
@Bean
JobsProperties jobsProperties() {
return JobsProperties.getJobsPropertiesDefaults();
}
@Bean
RestTemplate genieRestTemplate() {
return Mockito.mock(RestTemplate.class);
}
@Bean
WebEndpointProperties webEndpointProperties() {
return Mockito.mock(WebEndpointProperties.class);
}
@Bean
MeterRegistry meterRegistry() {
return Mockito.mock(MeterRegistry.class);
}
@Bean
GenieEventBus genieEventBus() {
return Mockito.mock(GenieEventBus.class);
}
@Bean
DataServices genieDataServices(final PersistenceService persistenceService) {
return new DataServices(persistenceService);
}
@Bean
PersistenceService geniePersistenceService() {
return Mockito.mock(PersistenceService.class);
}
@Bean
AgentRoutingService agentRoutingService() {
return Mockito.mock(AgentRoutingService.class);
}
}
/**
* Mock configuration for pretending zookeeper is enabled.
*/
@Configuration
static class ZookeeperMockConfig {
@Bean
LeaderInitiator leaderInitiatorFactoryBean() {
return Mockito.mock(LeaderInitiator.class);
}
}
}
| 2,441 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/tasks
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/tasks/leader/package-info.java
|
/*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Tests for this package.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.spring.autoconfigure.tasks.leader;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,442 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/tasks
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/tasks/node/NodeAutoConfigurationTest.java
|
/*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.spring.autoconfigure.tasks.node;
import com.netflix.genie.web.data.services.DataServices;
import com.netflix.genie.web.data.services.PersistenceService;
import com.netflix.genie.web.properties.DiskCleanupProperties;
import com.netflix.genie.web.properties.JobsProperties;
import com.netflix.genie.web.spring.autoconfigure.tasks.TasksAutoConfiguration;
import com.netflix.genie.web.tasks.node.DiskCleanupTask;
import io.micrometer.core.instrument.MeterRegistry;
import org.apache.commons.exec.Executor;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.Resource;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
/**
* Tests for {@link NodeAutoConfiguration}.
*
* @author tgianos
* @since 4.0.0
*/
class NodeAutoConfigurationTest {
private ApplicationContextRunner contextRunner =
new ApplicationContextRunner()
.withConfiguration(
AutoConfigurations.of(
NodeAutoConfiguration.class
)
)
.withUserConfiguration(MockBeanConfig.class);
/**
* All the expected beans exist.
*/
@Test
void expectedBeansExist() {
this.contextRunner.run(
context -> {
Assertions.assertThat(context).hasSingleBean(DiskCleanupProperties.class);
// Optional beans
Assertions.assertThat(context).doesNotHaveBean(DiskCleanupTask.class);
}
);
}
/**
* All the expected beans exist.
*/
@Test
void optionalBeansCreated() {
this.contextRunner
.withPropertyValues(
"genie.tasks.disk-cleanup.enabled=true"
)
.run(
context -> {
Assertions.assertThat(context).hasSingleBean(DiskCleanupProperties.class);
// Optional beans
Assertions.assertThat(context).hasSingleBean(DiskCleanupTask.class);
}
);
}
/**
* Configuration for beans that are dependencies of the auto configured beans in {@link TasksAutoConfiguration}.
*
* @author tgianos
* @since 4.0.0
*/
static class MockBeanConfig {
@Bean
ThreadPoolTaskScheduler genieTaskScheduler() {
return Mockito.mock(ThreadPoolTaskScheduler.class);
}
@Bean
PersistenceService geniePersistenceService() {
return Mockito.mock(PersistenceService.class);
}
@Bean
Resource jobsDir() {
final Resource resource = Mockito.mock(Resource.class);
Mockito.when(resource.exists()).thenReturn(true);
return resource;
}
@Bean
JobsProperties jobsProperties() {
return JobsProperties.getJobsPropertiesDefaults();
}
@Bean
MeterRegistry meterRegistry() {
return Mockito.mock(MeterRegistry.class);
}
@Bean
Executor executor() {
return Mockito.mock(Executor.class);
}
@Bean
DataServices genieDataServices(final PersistenceService persistenceService) {
final DataServices dataServices = Mockito.mock(DataServices.class);
Mockito.when(dataServices.getPersistenceService()).thenReturn(persistenceService);
return dataServices;
}
}
}
| 2,443 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/tasks
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/tasks/node/package-info.java
|
/*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Tests for this package.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.spring.autoconfigure.tasks.node;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,444 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/apis/ApisAutoConfigurationTest.java
|
/*
*
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.spring.autoconfigure.apis;
import com.netflix.genie.web.properties.HttpProperties;
import com.netflix.genie.web.properties.JobsProperties;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.UUID;
/**
* Unit tests for {@link ApisAutoConfiguration} beans.
*
* @author tgianos
* @since 3.0.0
*/
class ApisAutoConfigurationTest {
private ApisAutoConfiguration apisAutoConfiguration;
/**
* Setup for the tests.
*/
@BeforeEach
void setup() {
this.apisAutoConfiguration = new ApisAutoConfiguration();
}
/**
* Make sure we get a valid resource loader.
*/
@Test
void canGetResourceLoader() {
Assertions.assertThat(this.apisAutoConfiguration.resourceLoader()).isInstanceOf(DefaultResourceLoader.class);
}
/**
* Make sure we get a valid rest template to use.
*/
@Test
void canGetRestTemplate() {
Assertions
.assertThat(this.apisAutoConfiguration.genieRestTemplate(new HttpProperties(), new RestTemplateBuilder()))
.isNotNull();
}
/**
* Make sure the default implementation of a directory writer is used in this default configuration.
*/
@Test
void canGetDirectoryWriter() {
Assertions.assertThat(this.apisAutoConfiguration.directoryWriter()).isNotNull();
}
/**
* Test to make sure we can't create a jobs dir resource if the directory can't be created when the input jobs
* dir is invalid in any way.
*
* @throws IOException On error
*/
@Test
void cantGetJobsDirWhenJobsDirInvalid() throws IOException {
final ResourceLoader resourceLoader = Mockito.mock(ResourceLoader.class);
final URI jobsDirLocation = URI.create("file:/" + UUID.randomUUID().toString());
final JobsProperties jobsProperties = JobsProperties.getJobsPropertiesDefaults();
jobsProperties.getLocations().setJobs(jobsDirLocation);
final Resource tmpResource = Mockito.mock(Resource.class);
Mockito.when(resourceLoader.getResource(jobsDirLocation.toString())).thenReturn(tmpResource);
Mockito.when(tmpResource.exists()).thenReturn(true);
final File file = Mockito.mock(File.class);
Mockito.when(tmpResource.getFile()).thenReturn(file);
Mockito.when(file.isDirectory()).thenReturn(false);
Assertions
.assertThatIllegalStateException()
.isThrownBy(() -> this.apisAutoConfiguration.jobsDir(resourceLoader, jobsProperties))
.withMessage(jobsDirLocation + " exists but isn't a directory. Unable to continue");
final String localJobsDir = jobsDirLocation + "/";
Mockito.when(file.isDirectory()).thenReturn(true);
final Resource jobsDirResource = Mockito.mock(Resource.class);
Mockito.when(resourceLoader.getResource(localJobsDir)).thenReturn(jobsDirResource);
Mockito.when(tmpResource.exists()).thenReturn(false);
Mockito.when(jobsDirResource.exists()).thenReturn(false);
Mockito.when(jobsDirResource.getFile()).thenReturn(file);
Mockito.when(file.mkdirs()).thenReturn(false);
Assertions
.assertThatIllegalStateException()
.isThrownBy(() -> this.apisAutoConfiguration.jobsDir(resourceLoader, jobsProperties))
.withMessage("Unable to create jobs directory " + jobsDirLocation + " and it doesn't exist.");
}
/**
* Make sure we can get a valid job resource when all conditions are met.
*
* @throws IOException for any problem
*/
@Test
void canGetJobsDir() throws IOException {
final ResourceLoader resourceLoader = Mockito.mock(ResourceLoader.class);
final URI jobsDirLocation = URI.create("file:///" + UUID.randomUUID().toString() + "/");
final JobsProperties jobsProperties = JobsProperties.getJobsPropertiesDefaults();
jobsProperties.getLocations().setJobs(jobsDirLocation);
final Resource jobsDirResource = Mockito.mock(Resource.class);
Mockito.when(resourceLoader.getResource(jobsDirLocation.toString())).thenReturn(jobsDirResource);
Mockito.when(jobsDirResource.exists()).thenReturn(true);
final File file = Mockito.mock(File.class);
Mockito.when(jobsDirResource.getFile()).thenReturn(file);
Mockito.when(file.isDirectory()).thenReturn(true);
final Resource jobsDir = this.apisAutoConfiguration.jobsDir(resourceLoader, jobsProperties);
Assertions.assertThat(jobsDir).isNotNull();
}
}
| 2,445 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/apis/package-info.java
|
/*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Tests for this package.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.spring.autoconfigure.apis;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,446 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/apis/rest/v3
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/apis/rest/v3/hateoas/HateoasAutoConfigurationTest.java
|
/*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.spring.autoconfigure.apis.rest.v3.hateoas;
import com.netflix.genie.web.apis.rest.v3.hateoas.assemblers.ApplicationModelAssembler;
import com.netflix.genie.web.apis.rest.v3.hateoas.assemblers.ClusterModelAssembler;
import com.netflix.genie.web.apis.rest.v3.hateoas.assemblers.CommandModelAssembler;
import com.netflix.genie.web.apis.rest.v3.hateoas.assemblers.EntityModelAssemblers;
import com.netflix.genie.web.apis.rest.v3.hateoas.assemblers.JobExecutionModelAssembler;
import com.netflix.genie.web.apis.rest.v3.hateoas.assemblers.JobMetadataModelAssembler;
import com.netflix.genie.web.apis.rest.v3.hateoas.assemblers.JobModelAssembler;
import com.netflix.genie.web.apis.rest.v3.hateoas.assemblers.JobRequestModelAssembler;
import com.netflix.genie.web.apis.rest.v3.hateoas.assemblers.JobSearchResultModelAssembler;
import com.netflix.genie.web.apis.rest.v3.hateoas.assemblers.RootModelAssembler;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
/**
* Tests for sub auto configuration {@link HateoasAutoConfiguration}.
*
* @author tgianos
* @since 4.0.0
*/
class HateoasAutoConfigurationTest {
private final ApplicationContextRunner contextRunner =
new ApplicationContextRunner()
.withConfiguration(
AutoConfigurations.of(
HateoasAutoConfiguration.class
)
);
/**
* Make sure the configuration creates all the expected beans.
*/
@Test
void expectedHateoasBeansAreCreated() {
this.contextRunner.run(
context -> {
Assertions.assertThat(context).hasSingleBean(ApplicationModelAssembler.class);
Assertions.assertThat(context).hasSingleBean(ClusterModelAssembler.class);
Assertions.assertThat(context).hasSingleBean(CommandModelAssembler.class);
Assertions.assertThat(context).hasSingleBean(JobExecutionModelAssembler.class);
Assertions.assertThat(context).hasSingleBean(JobMetadataModelAssembler.class);
Assertions.assertThat(context).hasSingleBean(JobRequestModelAssembler.class);
Assertions.assertThat(context).hasSingleBean(JobModelAssembler.class);
Assertions.assertThat(context).hasSingleBean(JobSearchResultModelAssembler.class);
Assertions.assertThat(context).hasSingleBean(RootModelAssembler.class);
Assertions.assertThat(context).hasSingleBean(EntityModelAssemblers.class);
}
);
}
}
| 2,447 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/apis/rest/v3
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/apis/rest/v3/hateoas/package-info.java
|
/*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Tests for this package.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.spring.autoconfigure.apis.rest.v3.hateoas;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,448 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/health/HealthAutoConfigurationTest.java
|
/*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.spring.autoconfigure.health;
import com.netflix.genie.web.agent.services.AgentConnectionTrackingService;
import com.netflix.genie.web.health.GenieAgentHealthIndicator;
import com.netflix.genie.web.properties.JobsProperties;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Bean;
/**
* Unit tests for {@link HealthAutoConfiguration}.
*
* @author tgianos
* @since 4.0.0
*/
class HealthAutoConfigurationTest {
private ApplicationContextRunner contextRunner =
new ApplicationContextRunner()
.withConfiguration(
AutoConfigurations.of(
HealthAutoConfiguration.class
)
)
.withUserConfiguration(UserConfiguration.class);
/**
* Make sure expected beans are provided for health indicators.
*/
@Test
void healthBeansCreatedIfNoOthersExist() {
this.contextRunner.run(
context -> {
Assertions.assertThat(context).hasSingleBean(GenieAgentHealthIndicator.class);
}
);
}
/**
* Provide some junk beans if needed.
*/
static class UserConfiguration {
@Bean
JobsProperties jobsProperties() {
return Mockito.mock(JobsProperties.class);
}
@Bean
AgentConnectionTrackingService agentConnectionTrackingService() {
return Mockito.mock(AgentConnectionTrackingService.class);
}
}
}
| 2,449 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/health/package-info.java
|
/*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Tests for this package.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.spring.autoconfigure.health;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,450 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/agent/package-info.java
|
/*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Tests for this package.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.spring.autoconfigure.agent;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,451 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/agent/apis/rpc/v4
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/agent/apis/rpc/v4/interceptors/AgentRpcInterceptorsAutoConfigurationTest.java
|
/*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.spring.autoconfigure.agent.apis.rpc.v4.interceptors;
import com.netflix.genie.web.agent.apis.rpc.v4.interceptors.SimpleLoggingInterceptor;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Tests for {@link AgentRpcInterceptorsAutoConfiguration}.
*
* @author tgianos
* @since 4.0.0
*/
class AgentRpcInterceptorsAutoConfigurationTest {
private ApplicationContextRunner contextRunner =
new ApplicationContextRunner()
.withConfiguration(
AutoConfigurations.of(
AgentRpcInterceptorsAutoConfiguration.class
)
);
/**
* Default beans created.
*/
@Test
void expectedBeansExistIfGrpcEnabledAndNoUserBeans() {
this.contextRunner
.run(context -> Assertions.assertThat(context).hasSingleBean(SimpleLoggingInterceptor.class));
}
/**
* User beans override defaults.
*/
@Test
void expectedBeansExistWhenUserOverrides() {
this.contextRunner
.withUserConfiguration(UserConfig.class)
.run(
context -> {
Assertions.assertThat(context).hasSingleBean(SimpleLoggingInterceptor.class);
Assertions.assertThat(context.containsBean("userSimpleLoggingInterceptor")).isTrue();
}
);
}
/**
* Dummy user configuration.
*/
@Configuration
static class UserConfig {
@Bean
SimpleLoggingInterceptor userSimpleLoggingInterceptor() {
return Mockito.mock(SimpleLoggingInterceptor.class);
}
}
}
| 2,452 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/agent/apis/rpc/v4
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/agent/apis/rpc/v4/interceptors/package-info.java
|
/*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Tests for this package.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.spring.autoconfigure.agent.apis.rpc.v4.interceptors;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,453 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/agent/apis/rpc/v4
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/agent/apis/rpc/v4/endpoints/AgentRpcEndpointsAutoConfigurationTest.java
|
/*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.spring.autoconfigure.agent.apis.rpc.v4.endpoints;
import com.netflix.genie.common.internal.configs.ProtoConvertersAutoConfiguration;
import com.netflix.genie.common.internal.util.GenieHostInfo;
import com.netflix.genie.proto.FileStreamServiceGrpc;
import com.netflix.genie.proto.HeartBeatServiceGrpc;
import com.netflix.genie.proto.JobKillServiceGrpc;
import com.netflix.genie.proto.JobServiceGrpc;
import com.netflix.genie.proto.PingServiceGrpc;
import com.netflix.genie.web.agent.apis.rpc.v4.endpoints.GRpcAgentFileStreamServiceImpl;
import com.netflix.genie.web.agent.apis.rpc.v4.endpoints.GRpcHeartBeatServiceImpl;
import com.netflix.genie.web.agent.apis.rpc.v4.endpoints.GRpcJobServiceImpl;
import com.netflix.genie.web.agent.apis.rpc.v4.endpoints.GRpcPingServiceImpl;
import com.netflix.genie.web.agent.apis.rpc.v4.endpoints.JobServiceProtoErrorComposer;
import com.netflix.genie.web.agent.services.AgentConnectionTrackingService;
import com.netflix.genie.web.agent.services.AgentJobService;
import com.netflix.genie.web.agent.services.AgentRoutingService;
import com.netflix.genie.web.data.services.DataServices;
import com.netflix.genie.web.data.services.PersistenceService;
import com.netflix.genie.web.properties.AgentFileStreamProperties;
import com.netflix.genie.web.properties.HeartBeatProperties;
import com.netflix.genie.web.services.RequestForwardingService;
import io.micrometer.core.instrument.MeterRegistry;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.TaskScheduler;
/**
* Tests for {@link AgentRpcEndpointsAutoConfiguration}.
*
* @author tgianos
* @since 4.0.0
*/
class AgentRpcEndpointsAutoConfigurationTest {
private final ApplicationContextRunner contextRunner =
new ApplicationContextRunner()
.withConfiguration(
AutoConfigurations.of(
AgentRpcEndpointsAutoConfiguration.class,
ProtoConvertersAutoConfiguration.class
)
)
.withUserConfiguration(RequiredBeans.class);
/**
* Default beans created.
*/
@Test
void expectedBeansExistIfGrpcEnabledAndNoUserBeans() {
this.contextRunner
.run(
context -> {
Assertions.assertThat(context.containsBean("heartBeatServiceTaskScheduler")).isTrue();
Assertions.assertThat(context).hasSingleBean(JobServiceProtoErrorComposer.class);
Assertions
.assertThat(context)
.hasSingleBean(AgentFileStreamProperties.class);
Assertions
.assertThat(context)
.hasSingleBean(FileStreamServiceGrpc.FileStreamServiceImplBase.class);
Assertions
.assertThat(context)
.hasSingleBean(GRpcAgentFileStreamServiceImpl.class);
Assertions
.assertThat(context)
.hasSingleBean(HeartBeatProperties.class);
Assertions
.assertThat(context)
.hasSingleBean(HeartBeatServiceGrpc.HeartBeatServiceImplBase.class);
Assertions
.assertThat(context)
.hasSingleBean(GRpcHeartBeatServiceImpl.class);
Assertions
.assertThat(context)
.hasSingleBean(JobKillServiceGrpc.JobKillServiceImplBase.class);
Assertions
.assertThat(context)
.hasSingleBean(GRpcJobServiceImpl.class);
Assertions
.assertThat(context)
.hasSingleBean(JobServiceGrpc.JobServiceImplBase.class);
Assertions
.assertThat(context)
.hasSingleBean(GRpcJobServiceImpl.class);
Assertions
.assertThat(context)
.hasSingleBean(PingServiceGrpc.PingServiceImplBase.class);
Assertions
.assertThat(context)
.hasSingleBean(GRpcPingServiceImpl.class);
}
);
}
/**
* User beans override defaults.
*/
@Test
void expectedBeansExistWhenUserOverrides() {
this.contextRunner
.withUserConfiguration(UserConfig.class)
.run(
context -> {
Assertions.assertThat(context.containsBean("heartBeatServiceTaskScheduler")).isTrue();
Assertions.assertThat(context).hasSingleBean(JobServiceProtoErrorComposer.class);
Assertions
.assertThat(context)
.hasSingleBean(AgentFileStreamProperties.class);
Assertions
.assertThat(context)
.hasSingleBean(FileStreamServiceGrpc.FileStreamServiceImplBase.class);
Assertions
.assertThat(context)
.doesNotHaveBean(GRpcAgentFileStreamServiceImpl.class);
Assertions
.assertThat(context)
.hasSingleBean(HeartBeatProperties.class);
Assertions
.assertThat(context)
.hasSingleBean(HeartBeatServiceGrpc.HeartBeatServiceImplBase.class);
Assertions
.assertThat(context)
.doesNotHaveBean(GRpcHeartBeatServiceImpl.class);
Assertions
.assertThat(context)
.hasSingleBean(JobKillServiceGrpc.JobKillServiceImplBase.class);
Assertions
.assertThat(context)
.doesNotHaveBean(GRpcJobServiceImpl.class);
Assertions
.assertThat(context)
.hasSingleBean(JobServiceGrpc.JobServiceImplBase.class);
Assertions
.assertThat(context)
.doesNotHaveBean(GRpcJobServiceImpl.class);
Assertions
.assertThat(context)
.hasSingleBean(PingServiceGrpc.PingServiceImplBase.class);
Assertions
.assertThat(context)
.doesNotHaveBean(GRpcPingServiceImpl.class);
Assertions.assertThat(context.containsBean("userJobServiceProtoErrorComposer")).isTrue();
}
);
}
/**
* Mocking needed required beans provided by other configurations.
*/
static class RequiredBeans {
@Bean
TaskScheduler genieTaskScheduler() {
return Mockito.mock(TaskScheduler.class);
}
@Bean
AgentConnectionTrackingService agentConnectionTrackingService() {
return Mockito.mock(AgentConnectionTrackingService.class);
}
@Bean
PersistenceService geniePersistenceService() {
return Mockito.mock(PersistenceService.class);
}
@Bean
AgentJobService agentJobService() {
return Mockito.mock(AgentJobService.class);
}
@Bean
GenieHostInfo genieHostInfo() {
return Mockito.mock(GenieHostInfo.class);
}
@Bean
MeterRegistry meterRegistry() {
return Mockito.mock(MeterRegistry.class);
}
@Bean
DataServices genieDataServices(final PersistenceService persistenceService) {
final DataServices dataServices = Mockito.mock(DataServices.class);
Mockito.when(dataServices.getPersistenceService()).thenReturn(persistenceService);
return dataServices;
}
@Bean
AgentRoutingService agentRoutingService() {
return Mockito.mock(AgentRoutingService.class);
}
@Bean
RequestForwardingService requestForwardingService() {
return Mockito.mock(RequestForwardingService.class);
}
}
/**
* Dummy user configuration.
*/
static class UserConfig {
@Bean(name = "heartBeatServiceTaskScheduler")
TaskScheduler userHeartBeatScheduler() {
return Mockito.mock(TaskScheduler.class);
}
@Bean
JobServiceProtoErrorComposer userJobServiceProtoErrorComposer() {
return Mockito.mock(JobServiceProtoErrorComposer.class);
}
@Bean
FileStreamServiceGrpc.FileStreamServiceImplBase userGRpcAgentFileStreamService() {
return Mockito.mock(FileStreamServiceGrpc.FileStreamServiceImplBase.class);
}
@Bean
HeartBeatServiceGrpc.HeartBeatServiceImplBase userGRpcHeartBeatService() {
return Mockito.mock(HeartBeatServiceGrpc.HeartBeatServiceImplBase.class);
}
@Bean
JobKillServiceGrpc.JobKillServiceImplBase userGRpcJobKillService() {
return Mockito.mock(JobKillServiceGrpc.JobKillServiceImplBase.class);
}
@Bean
JobServiceGrpc.JobServiceImplBase userGRpcJobService() {
return Mockito.mock(JobServiceGrpc.JobServiceImplBase.class);
}
@Bean
PingServiceGrpc.PingServiceImplBase userGRpcPingService() {
return Mockito.mock(PingServiceGrpc.PingServiceImplBase.class);
}
}
}
| 2,454 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/agent/apis/rpc/v4
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/agent/apis/rpc/v4/endpoints/package-info.java
|
/*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Tests for this package.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.spring.autoconfigure.agent.apis.rpc.v4.endpoints;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,455 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/agent/apis/rpc
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/agent/apis/rpc/servers/AgentRpcServersAutoConfigurationTest.java
|
/*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.spring.autoconfigure.agent.apis.rpc.servers;
import brave.Tracing;
import com.netflix.genie.web.agent.apis.rpc.servers.GRpcServerManager;
import com.netflix.genie.web.properties.GRpcServerProperties;
import io.grpc.Server;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Bean;
/**
* Tests for {@link AgentRpcServersAutoConfiguration}.
*
* @author tgianos
* @since 4.0.0
*/
class AgentRpcServersAutoConfigurationTest {
private final ApplicationContextRunner contextRunner =
new ApplicationContextRunner()
.withConfiguration(
AutoConfigurations.of(
AgentRpcServersAutoConfiguration.class
)
)
.withUserConfiguration(ExternalBeans.class);
/**
* Default beans should be created.
*/
@Test
void expectedBeansExistIfGrpcEnabledAndNoUserBeans() {
this.contextRunner
.run(
context -> {
Assertions.assertThat(context).hasSingleBean(GRpcServerProperties.class);
Assertions.assertThat(context).hasSingleBean(Server.class);
Assertions.assertThat(context).hasSingleBean(GRpcServerManager.class);
}
);
}
/**
* User beans override default beans.
*/
@Test
void expectedBeansExistWhenUserOverrides() {
this.contextRunner
.withUserConfiguration(UserConfig.class)
.run(
context -> {
Assertions.assertThat(context).hasSingleBean(GRpcServerProperties.class);
Assertions.assertThat(context).hasSingleBean(Server.class);
Assertions.assertThat(context).hasSingleBean(GRpcServerManager.class);
Assertions.assertThat(context.containsBean("userServer")).isTrue();
Assertions.assertThat(context.containsBean("userServerManager")).isTrue();
Assertions.assertThat(context.containsBean("gRpcServer")).isFalse();
Assertions.assertThat(context.containsBean("gRpcServerManager")).isFalse();
}
);
}
private static class ExternalBeans {
@Bean
Tracing tracing() {
return Tracing.newBuilder().build();
}
}
private static class UserConfig {
@Bean
Server userServer() {
return Mockito.mock(Server.class);
}
@Bean
GRpcServerManager userServerManager() {
return Mockito.mock(GRpcServerManager.class);
}
}
}
| 2,456 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/agent/apis/rpc
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/agent/apis/rpc/servers/package-info.java
|
/*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Tests for this package.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.spring.autoconfigure.agent.apis.rpc.servers;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,457 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/agent
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/agent/resources/AgentResourcesAutoConfigurationTest.java
|
/*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.spring.autoconfigure.agent.resources;
import org.junit.jupiter.api.Test;
/**
* Tests for {@link AgentResourcesAutoConfiguration}.
*
* @author tgianos
* @since 4.0.0
*/
class AgentResourcesAutoConfigurationTest {
/**
* Get a valid agent file protocol resolver.
*/
@Test
void canGetAgentFileProtocolResolver() {
// Assert.assertNotNull(
// this.apisAutoConfiguration.agentFileProtocolResolver(
// Mockito.mock(AgentFileStreamService.class)
// )
// );
}
/**
* Get a valid agent file protocol resolver registrar.
*/
@Test
void canGetAgentFileProtocolResolverRegistrar() {
// Assert.assertNotNull(
// this.apisAutoConfiguration.agentFileProtocolResolverRegistrar(
// Mockito.mock(AgentFileProtocolResolver.class)
// )
// );
}
}
| 2,458 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/agent
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/agent/resources/package-info.java
|
/*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Tests for this package.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.spring.autoconfigure.agent.resources;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,459 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/agent
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/agent/launchers/AgentLaunchersAutoConfigurationTest.java
|
/*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.spring.autoconfigure.agent.launchers;
import brave.Tracer;
import com.netflix.genie.common.internal.tracing.brave.BraveTagAdapter;
import com.netflix.genie.common.internal.tracing.brave.BraveTracePropagator;
import com.netflix.genie.common.internal.tracing.brave.BraveTracingCleanup;
import com.netflix.genie.common.internal.tracing.brave.BraveTracingComponents;
import com.netflix.genie.web.agent.launchers.impl.LocalAgentLauncherImpl;
import com.netflix.genie.web.agent.launchers.impl.TitusAgentLauncherImpl;
import com.netflix.genie.web.data.services.DataServices;
import com.netflix.genie.web.data.services.PersistenceService;
import com.netflix.genie.web.introspection.GenieWebHostInfo;
import com.netflix.genie.web.introspection.GenieWebRpcInfo;
import com.netflix.genie.web.properties.LocalAgentLauncherProperties;
import com.netflix.genie.web.properties.TitusAgentLauncherProperties;
import com.netflix.genie.web.util.ExecutorFactory;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import java.util.UUID;
/**
* Tests for {@link AgentLaunchersAutoConfiguration}.
*
* @author tgianos
* @since 4.0.0
*/
class AgentLaunchersAutoConfigurationTest {
private final ApplicationContextRunner contextRunner =
new ApplicationContextRunner()
.withConfiguration(
AutoConfigurations.of(
AgentLaunchersAutoConfiguration.class
)
)
.withUserConfiguration(UserConfig.class);
/**
* All the expected beans should exist when the auto configuration is applied.
*/
@Test
void testExpectedBeansExist() {
this.contextRunner
.withPropertyValues(
"genie.agent.launcher.local.enabled=true"
)
.run(
context -> {
Assertions.assertThat(context).hasSingleBean(LocalAgentLauncherProperties.class);
Assertions.assertThat(context).hasSingleBean(TitusAgentLauncherProperties.class);
Assertions.assertThat(context).hasSingleBean(ExecutorFactory.class);
Assertions.assertThat(context).hasSingleBean(LocalAgentLauncherImpl.class);
Assertions.assertThat(context).doesNotHaveBean(TitusAgentLauncherImpl.TitusJobRequestAdapter.class);
Assertions.assertThat(context).doesNotHaveBean(TitusAgentLauncherImpl.class);
Assertions.assertThat(context).doesNotHaveBean("titusAPIRetryPolicy");
Assertions.assertThat(context).doesNotHaveBean(TitusAgentLauncherImpl.TitusAPIRetryPolicy.class);
Assertions.assertThat(context).doesNotHaveBean("titusAPIBackoffPolicy");
Assertions.assertThat(context).doesNotHaveBean("titusAPIRetryTemplate");
Assertions.assertThat(context).doesNotHaveBean("titusRestTemplate");
}
);
}
/**
* .
*/
@Test
void testTitusAgentLauncherOnlyBean() {
this.contextRunner
.withPropertyValues(
"genie.agent.launcher.titus.enabled=true",
"genie.agent.launcher.local.enabled=false"
)
.run(
context -> {
Assertions.assertThat(context).hasSingleBean(LocalAgentLauncherProperties.class);
Assertions.assertThat(context).hasSingleBean(TitusAgentLauncherProperties.class);
Assertions.assertThat(context).hasBean("titusAPIRetryPolicy");
Assertions.assertThat(context).hasSingleBean(TitusAgentLauncherImpl.TitusAPIRetryPolicy.class);
Assertions.assertThat(context).hasBean("titusAPIBackoffPolicy");
Assertions.assertThat(context).hasBean("titusAPIRetryTemplate");
Assertions.assertThat(context).hasBean("titusRestTemplate");
Assertions.assertThat(context).hasSingleBean(TitusAgentLauncherImpl.TitusJobRequestAdapter.class);
Assertions.assertThat(context).hasSingleBean(TitusAgentLauncherImpl.class);
Assertions.assertThat(context).doesNotHaveBean(LocalAgentLauncherImpl.class);
}
);
}
static class UserConfig {
@Bean
GenieWebHostInfo genieWebHostInfo() {
return new GenieWebHostInfo(UUID.randomUUID().toString());
}
@Bean
GenieWebRpcInfo genieWebRpcInfo() {
return new GenieWebRpcInfo(33_433);
}
@Bean
PersistenceService geniePersistenceService() {
return Mockito.mock(PersistenceService.class);
}
@Bean
DataServices genieDataServices(final PersistenceService persistenceService) {
final DataServices dataServices = Mockito.mock(DataServices.class);
Mockito.when(dataServices.getPersistenceService()).thenReturn(persistenceService);
return dataServices;
}
@Bean
MeterRegistry meterRegistry() {
return new SimpleMeterRegistry();
}
@Bean
RestTemplateBuilder restTemplateBuilder() {
return new RestTemplateBuilder();
}
@Bean
BraveTracingComponents genieTracingComponents() {
return new BraveTracingComponents(
Mockito.mock(Tracer.class),
Mockito.mock(BraveTracePropagator.class),
Mockito.mock(BraveTracingCleanup.class),
Mockito.mock(BraveTagAdapter.class)
);
}
}
}
| 2,460 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/agent
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/agent/launchers/package-info.java
|
/*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Tests for this package.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.spring.autoconfigure.agent.launchers;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,461 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/agent
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/agent/inspectors/AgentInspectorsAutoConfigurationTest.java
|
/*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.spring.autoconfigure.agent.inspectors;
import com.netflix.genie.web.agent.inspectors.AgentMetadataInspector;
import com.netflix.genie.web.agent.inspectors.impl.BlacklistedVersionAgentMetadataInspector;
import com.netflix.genie.web.agent.inspectors.impl.MinimumVersionAgentMetadataInspector;
import com.netflix.genie.web.agent.inspectors.impl.RejectAllJobsAgentMetadataInspector;
import com.netflix.genie.web.agent.inspectors.impl.WhitelistedVersionAgentMetadataInspector;
import com.netflix.genie.web.properties.AgentFilterProperties;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
/**
* Tests for {@link AgentInspectorsAutoConfiguration}.
*
* @author mprimi
* @since 4.0.0
*/
class AgentInspectorsAutoConfigurationTest {
private final ApplicationContextRunner contextRunner =
new ApplicationContextRunner()
.withConfiguration(
AutoConfigurations.of(
AgentInspectorsAutoConfiguration.class
)
);
/**
* Test expected context when configuration is enabled.
*/
@Test
void testContextIfEnabled() {
this.contextRunner
.withPropertyValues(
"genie.agent.filter.enabled=true"
)
.run(
(context) -> {
Assertions.assertThat(context).hasSingleBean(AgentFilterProperties.class);
Assertions.assertThat(context).getBeans(AgentMetadataInspector.class).hasSize(4);
Assertions.assertThat(context).hasSingleBean(WhitelistedVersionAgentMetadataInspector.class);
Assertions.assertThat(context).hasSingleBean(BlacklistedVersionAgentMetadataInspector.class);
Assertions.assertThat(context).hasSingleBean(MinimumVersionAgentMetadataInspector.class);
Assertions.assertThat(context).hasSingleBean(RejectAllJobsAgentMetadataInspector.class);
}
);
}
/**
* Test expected context when configuration is disabled.
*/
@Test
void testContextIfDisabled() {
this.contextRunner
.withPropertyValues(
"genie.agent.filter.enabled=nope"
)
.run(
(context) -> {
Assertions.assertThat(context).doesNotHaveBean(AgentFilterProperties.class);
Assertions.assertThat(context).doesNotHaveBean(AgentMetadataInspector.class);
}
);
}
/**
* Test expected context when configuration is not explicitly enabled or disabled.
*/
@Test
void testContextIfUnspecified() {
this.contextRunner
.withPropertyValues(
"genie.some.other.property=true"
)
.run(
(context) -> {
Assertions.assertThat(context).doesNotHaveBean(AgentFilterProperties.class);
Assertions.assertThat(context).doesNotHaveBean(AgentMetadataInspector.class);
}
);
}
}
| 2,462 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/agent
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/agent/inspectors/package-info.java
|
/*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Tests for this package.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.spring.autoconfigure.agent.inspectors;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,463 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/agent
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/agent/services/AgentServicesAutoConfigurationTest.java
|
/*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.spring.autoconfigure.agent.services;
import com.netflix.genie.common.internal.util.GenieHostInfo;
import com.netflix.genie.common.internal.util.PropertiesMapCache;
import com.netflix.genie.web.agent.inspectors.AgentMetadataInspector;
import com.netflix.genie.web.agent.services.AgentConfigurationService;
import com.netflix.genie.web.agent.services.AgentConnectionTrackingService;
import com.netflix.genie.web.agent.services.AgentFilterService;
import com.netflix.genie.web.agent.services.AgentJobService;
import com.netflix.genie.web.agent.services.AgentRoutingService;
import com.netflix.genie.web.agent.services.impl.AgentRoutingServiceCuratorDiscoveryImpl;
import com.netflix.genie.web.data.services.DataServices;
import com.netflix.genie.web.data.services.PersistenceService;
import com.netflix.genie.web.properties.AgentConfigurationProperties;
import com.netflix.genie.web.properties.AgentConnectionTrackingServiceProperties;
import com.netflix.genie.web.properties.AgentRoutingServiceProperties;
import com.netflix.genie.web.services.JobResolverService;
import com.netflix.genie.web.spring.autoconfigure.agent.apis.rpc.v4.endpoints.AgentRpcEndpointsAutoConfiguration;
import io.micrometer.core.instrument.MeterRegistry;
import org.apache.curator.framework.listen.Listenable;
import org.apache.curator.framework.state.ConnectionStateListener;
import org.apache.curator.x.discovery.ServiceDiscovery;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
/**
* Tests for {@link AgentRpcEndpointsAutoConfiguration}.
*
* @author mprimi
* @since 4.0.0
*/
class AgentServicesAutoConfigurationTest {
private ApplicationContextRunner contextRunner =
new ApplicationContextRunner()
.withConfiguration(
AutoConfigurations.of(
AgentServicesAutoConfiguration.class
)
)
.withUserConfiguration(RequiredBeans.class);
/**
* Verify beans in case Zookeeper is not enabled.
*/
@Test
void expectedBeansExistWithZookeeperDisabled() {
this.contextRunner
.run(
context -> {
Assertions.assertThat(context).doesNotHaveBean(ServiceDiscovery.class);
Assertions.assertThat(context).hasSingleBean(AgentRoutingService.class);
Assertions.assertThat(context).hasSingleBean(AgentJobService.class);
Assertions.assertThat(context).hasSingleBean(AgentConnectionTrackingService.class);
Assertions.assertThat(context).hasSingleBean(AgentFilterService.class);
Assertions.assertThat(context).hasSingleBean(AgentConfigurationProperties.class);
Assertions.assertThat(context).hasSingleBean(AgentConfigurationService.class);
Assertions.assertThat(context).hasSingleBean(AgentRoutingServiceProperties.class);
Assertions.assertThat(context).hasSingleBean(AgentConnectionTrackingServiceProperties.class);
}
);
}
/**
* Verify beans in case Zookeeper is enabled.
*/
@Test
void expectedBeansExistWithZookeeperEnabled() {
this.contextRunner
.withUserConfiguration(ZookeeperMockConfig.class)
.run(
context -> {
Assertions.assertThat(context).hasSingleBean(ServiceDiscovery.class);
Assertions.assertThat(context).hasSingleBean(AgentJobService.class);
Assertions.assertThat(context).hasSingleBean(AgentConnectionTrackingService.class);
Assertions.assertThat(context).hasSingleBean(AgentRoutingService.class);
Assertions.assertThat(context).hasSingleBean(AgentFilterService.class);
Assertions.assertThat(context).hasSingleBean(AgentConfigurationProperties.class);
Assertions.assertThat(context).hasSingleBean(AgentConfigurationService.class);
Assertions.assertThat(context).hasSingleBean(AgentRoutingServiceProperties.class);
Assertions.assertThat(context).hasSingleBean(AgentConnectionTrackingServiceProperties.class);
}
);
}
static class RequiredBeans {
@Bean
DataServices dataServices() {
return Mockito.mock(DataServices.class);
}
@Bean
JobResolverService jobResolverService() {
return Mockito.mock(JobResolverService.class);
}
@Bean
MeterRegistry meterRegistry() {
return Mockito.mock(MeterRegistry.class);
}
@Bean(name = "genieTaskScheduler")
TaskScheduler taskScheduler() {
return Mockito.mock(TaskScheduler.class);
}
@Bean
GenieHostInfo genieHostInfo() {
return Mockito.mock(GenieHostInfo.class);
}
@Bean
AgentMetadataInspector agentMetadataInspector() {
return Mockito.mock(AgentMetadataInspector.class);
}
@Bean
PersistenceService geniePersistenceService() {
return Mockito.mock(PersistenceService.class);
}
@Bean
PropertiesMapCache.Factory propertiesMapCacheFactory() {
return Mockito.mock(PropertiesMapCache.Factory.class);
}
}
/**
* Mock configuration for pretending zookeeper is enabled.
*/
@Configuration
static class ZookeeperMockConfig {
@Bean
@SuppressWarnings("unchecked")
ServiceDiscovery<AgentRoutingServiceCuratorDiscoveryImpl.Agent> serviceDiscovery() {
return Mockito.mock(ServiceDiscovery.class);
}
@Bean
@SuppressWarnings("unchecked")
Listenable<ConnectionStateListener> listenableCuratorConnectionState() {
return Mockito.mock(Listenable.class);
}
}
}
| 2,464 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/agent
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/agent/services/package-info.java
|
/*
*
* Copyright 2020 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Tests for this package.
*
* @author mprimi
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.spring.autoconfigure.agent.services;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,465 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/introspection/IntrospectionAutoConfigurationTest.java
|
/*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.spring.autoconfigure.introspection;
import com.netflix.genie.web.introspection.GenieWebHostInfo;
import com.netflix.genie.web.introspection.GenieWebRpcInfo;
import io.grpc.Server;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Bean;
import java.net.InetAddress;
/**
* Tests for {@link IntrospectionAutoConfiguration}.
*
* @author tgianos
* @since 4.0.0
*/
class IntrospectionAutoConfigurationTest {
private static final int EXPECTED_SERVER_PORT = 2482;
private ApplicationContextRunner contextRunner =
new ApplicationContextRunner()
.withConfiguration(
AutoConfigurations.of(
IntrospectionAutoConfiguration.class
)
);
/**
* Make sure when the gRPC server starts as expected the bean is created.
*/
@Test
void expectedBeansCreated() {
this.contextRunner
.withUserConfiguration(ServerStartedConfiguration.class)
.run(
context -> {
Assertions.assertThat(context).hasSingleBean(GenieWebHostInfo.class);
final GenieWebHostInfo hostInfo = context.getBean(GenieWebHostInfo.class);
Assertions
.assertThat(hostInfo.getHostname())
.isEqualTo(InetAddress.getLocalHost().getCanonicalHostName());
Assertions.assertThat(context).hasSingleBean(GenieWebRpcInfo.class);
final GenieWebRpcInfo rpcInfo = context.getBean(GenieWebRpcInfo.class);
Assertions.assertThat(rpcInfo.getRpcPort()).isEqualTo(EXPECTED_SERVER_PORT);
}
);
}
/**
* Make sure when the gRPC server doesn't start within the retry context the expected exception is thrown.
*/
@Test
void expectedExceptionThrownWhenServerIsNotStarted() {
this.contextRunner
.withUserConfiguration(ServerNeverStartsConfiguration.class)
.run(
context -> Assertions
.assertThat(context)
.getFailure()
.hasRootCauseExactlyInstanceOf(IllegalStateException.class)
);
}
/**
* Make sure when the gRPC server is already terminated we get expected exception.
*/
@Test
void expectedExceptionThrownWhenServerAlreadyTerminated() {
this.contextRunner
.withUserConfiguration(ServerAlreadyTerminatedConfiguration.class)
.run(
context -> Assertions
.assertThat(context)
.getFailure()
.hasRootCauseExactlyInstanceOf(IllegalStateException.class)
);
}
/**
* Make sure when the gRPC server is already shutdown we get expected exception.
*/
@Test
void expectedExceptionThrownWhenServerAlreadyShutdown() {
this.contextRunner
.withUserConfiguration(ServerAlreadyShutdownConfiguration.class)
.run(
context -> Assertions
.assertThat(context)
.getFailure()
.hasRootCauseExactlyInstanceOf(IllegalStateException.class)
);
}
static class ServerStartedConfiguration {
@Bean
Server mockGRpcServer() {
final Server server = Mockito.mock(Server.class);
Mockito.when(server.isTerminated()).thenReturn(false);
Mockito.when(server.isShutdown()).thenReturn(false);
Mockito.when(server.getPort()).thenReturn(EXPECTED_SERVER_PORT);
return server;
}
}
static class ServerNeverStartsConfiguration {
@Bean
Server mockGRpcServer() {
final Server server = Mockito.mock(Server.class);
Mockito.when(server.isTerminated()).thenReturn(false);
Mockito.when(server.isShutdown()).thenReturn(false);
Mockito.when(server.getPort()).thenReturn(-1);
return server;
}
}
static class ServerAlreadyTerminatedConfiguration {
@Bean
Server mockGRpcServer() {
final Server server = Mockito.mock(Server.class);
Mockito.when(server.isTerminated()).thenReturn(true);
Mockito.when(server.isShutdown()).thenReturn(false);
return server;
}
}
static class ServerAlreadyShutdownConfiguration {
@Bean
Server mockGRpcServer() {
final Server server = Mockito.mock(Server.class);
Mockito.when(server.isTerminated()).thenReturn(false);
Mockito.when(server.isShutdown()).thenReturn(true);
return server;
}
}
}
| 2,466 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/introspection/package-info.java
|
/*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Tests for this package.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.spring.autoconfigure.introspection;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,467 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/properties
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/properties/converters/PropertyConvertersAutoConfigurationTest.java
|
/*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.spring.autoconfigure.properties.converters;
import com.netflix.genie.web.properties.converters.URIPropertyConverter;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
/**
* Tests for {@link PropertyConvertersAutoConfiguration}.
*
* @author tgianos
* @since 4.0.0
*/
class PropertyConvertersAutoConfigurationTest {
private ApplicationContextRunner contextRunner =
new ApplicationContextRunner()
.withConfiguration(
AutoConfigurations.of(
PropertyConvertersAutoConfiguration.class
)
);
/**
* Make sure the expected converters are created.
*/
@Test
void canCreateExpectedConverters() {
this.contextRunner.run(
context -> {
Assertions.assertThat(context).hasSingleBean(URIPropertyConverter.class);
}
);
}
}
| 2,468 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/properties
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/properties/converters/package-info.java
|
/*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Tests for this package.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.spring.autoconfigure.properties.converters;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,469 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/scripts/ScriptsAutoConfigurationTest.java
|
/*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.spring.autoconfigure.scripts;
import com.netflix.genie.common.internal.util.PropertiesMapCache;
import com.netflix.genie.web.properties.AgentLauncherSelectorScriptProperties;
import com.netflix.genie.web.properties.ClusterSelectorScriptProperties;
import com.netflix.genie.web.properties.CommandSelectorManagedScriptProperties;
import com.netflix.genie.web.scripts.AgentLauncherSelectorManagedScript;
import com.netflix.genie.web.scripts.ClusterSelectorManagedScript;
import com.netflix.genie.web.scripts.CommandSelectorManagedScript;
import com.netflix.genie.web.scripts.ScriptManager;
import io.micrometer.core.instrument.MeterRegistry;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ResourceLoader;
import org.springframework.scheduling.TaskScheduler;
/**
* Tests for {@link ScriptsAutoConfiguration}.
*
* @author mprimi
* @since 4.0.0
*/
class ScriptsAutoConfigurationTest {
private ApplicationContextRunner contextRunner =
new ApplicationContextRunner()
.withUserConfiguration(MocksConfiguration.class)
.withConfiguration(
AutoConfigurations.of(
ScriptsAutoConfiguration.class
)
);
@Test
void scriptsNotCreatedByDefault() {
this.contextRunner
.run(
context -> {
Assertions.assertThat(context).hasSingleBean(ClusterSelectorScriptProperties.class);
Assertions.assertThat(context).hasSingleBean(CommandSelectorManagedScriptProperties.class);
Assertions.assertThat(context).hasSingleBean(AgentLauncherSelectorScriptProperties.class);
Assertions.assertThat(context).hasSingleBean(ScriptManager.class);
Assertions.assertThat(context).doesNotHaveBean(ClusterSelectorManagedScript.class);
Assertions.assertThat(context).doesNotHaveBean(CommandSelectorManagedScript.class);
Assertions.assertThat(context).doesNotHaveBean(AgentLauncherSelectorManagedScript.class);
Assertions.assertThat(context).hasSingleBean(ScriptsAutoConfiguration.ManagedScriptPreLoader.class);
}
);
}
@Test
void scriptsCreatedIfSourceIsConfigured() {
this.contextRunner
.withPropertyValues(
ClusterSelectorScriptProperties.SOURCE_PROPERTY + "=file:///script.js",
CommandSelectorManagedScriptProperties.SOURCE_PROPERTY + "=file:///script.groovy",
AgentLauncherSelectorScriptProperties.SOURCE_PROPERTY + "=file:///script.groovy"
)
.run(
context -> {
Assertions.assertThat(context).hasSingleBean(ClusterSelectorScriptProperties.class);
Assertions.assertThat(context).hasSingleBean(CommandSelectorManagedScriptProperties.class);
Assertions.assertThat(context).hasSingleBean(AgentLauncherSelectorScriptProperties.class);
Assertions.assertThat(context).hasSingleBean(ScriptManager.class);
Assertions.assertThat(context).hasSingleBean(ClusterSelectorManagedScript.class);
Assertions.assertThat(context).hasSingleBean(CommandSelectorManagedScript.class);
Assertions.assertThat(context).hasSingleBean(AgentLauncherSelectorManagedScript.class);
Assertions.assertThat(context).hasSingleBean(ScriptsAutoConfiguration.ManagedScriptPreLoader.class);
}
);
}
static class MocksConfiguration {
@Bean
@Qualifier("genieTaskScheduler")
TaskScheduler taskScheduler() {
return Mockito.mock(TaskScheduler.class);
}
@Bean
MeterRegistry meterRegistry() {
return Mockito.mock(MeterRegistry.class);
}
@Bean
ResourceLoader resourceLoader() {
return Mockito.mock(ResourceLoader.class);
}
@Bean
PropertiesMapCache.Factory propertiesMapCacheFactory() {
return Mockito.mock(PropertiesMapCache.Factory.class);
}
}
}
| 2,470 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/scripts/package-info.java
|
/*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Tests for script extensions configuration.
*
* @author mprimi
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.spring.autoconfigure.scripts;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,471 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/aws/AWSAutoConfigurationTest.java
|
/*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.spring.autoconfigure.aws;
import com.amazonaws.retry.RetryPolicy;
import com.amazonaws.services.sns.AmazonSNS;
import io.awspring.cloud.autoconfigure.context.ContextCredentialsAutoConfiguration;
import io.awspring.cloud.autoconfigure.context.ContextRegionProviderAutoConfiguration;
import io.awspring.cloud.autoconfigure.context.ContextResourceLoaderAutoConfiguration;
import io.awspring.cloud.core.config.AmazonWebserviceClientConfigurationUtils;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
/**
* Tests for behavior of {@link AWSAutoConfiguration}.
*
* @author mprimi
* @since 4.0.0
*/
class AWSAutoConfigurationTest {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(
AutoConfigurations.of(
AWSAutoConfiguration.class,
ContextCredentialsAutoConfiguration.class,
ContextRegionProviderAutoConfiguration.class,
ContextResourceLoaderAutoConfiguration.class,
com.netflix.genie.common.internal.configs.AwsAutoConfiguration.class
)
)
.withPropertyValues(
"genie.retry.sns.noOfRetries=3",
"genie.notifications.sns.enabled=true",
"cloud.aws.credentials.useDefaultAwsCredentialsChain=true",
"cloud.aws.region.auto=false",
"cloud.aws.region.static=us-east-1",
"cloud.aws.stack.auto=false",
"spring.jmx.enabled=false",
"spring.main.webApplicationType=none"
);
/**
* Test expected context.
*/
@Test
void testExpectedContext() {
this.contextRunner.run(
(context) -> {
Assertions.assertThat(context).hasBean(AWSAutoConfiguration.SNS_CLIENT_BEAN_NAME);
Assertions.assertThat(context).hasBean("SNSClientRetryPolicy");
Assertions.assertThat(context).hasBean("SNSClientConfiguration");
Assertions.assertThat(
context.getBean("SNSClientRetryPolicy", RetryPolicy.class).getMaxErrorRetry()
).isEqualTo(3);
}
);
}
/**
* Test expected context with SNS disabled via property.
*/
@Test
void testExpectedContextWhenSNSDisabled() {
this.contextRunner
.withPropertyValues(
"genie.notifications.sns.enabled=false"
).run(
(context) -> {
Assertions.assertThat(context).doesNotHaveBean(AWSAutoConfiguration.SNS_CLIENT_BEAN_NAME);
}
);
}
/**
* Test that the name qualifier for the custom AmazonSNS bean matches the one generated as part of Spring Cloud
* AWS Messaging configuration (and hence the latter is not created).
*/
@Test
void testSpringCloudAWSBeanNameOverride() {
Assertions.assertThat(
AmazonWebserviceClientConfigurationUtils.getBeanName(String.valueOf(AmazonSNS.class))
).isEqualTo(AWSAutoConfiguration.SNS_CLIENT_BEAN_NAME);
}
}
| 2,472 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/aws/package-info.java
|
/*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Test for AWS autoconfigurations.
*/
package com.netflix.genie.web.spring.autoconfigure.aws;
| 2,473 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/data/DataAutoConfigurationTest.java
|
/*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.spring.autoconfigure.data;
import com.netflix.genie.web.data.services.DataServices;
import com.netflix.genie.web.data.services.impl.jpa.JpaPersistenceServiceImpl;
import com.netflix.genie.web.data.services.impl.jpa.repositories.JpaApplicationRepository;
import com.netflix.genie.web.data.services.impl.jpa.repositories.JpaClusterRepository;
import com.netflix.genie.web.data.services.impl.jpa.repositories.JpaCommandRepository;
import com.netflix.genie.web.data.services.impl.jpa.repositories.JpaCriterionRepository;
import com.netflix.genie.web.data.services.impl.jpa.repositories.JpaFileRepository;
import com.netflix.genie.web.data.services.impl.jpa.repositories.JpaJobRepository;
import com.netflix.genie.web.data.services.impl.jpa.repositories.JpaRepositories;
import com.netflix.genie.web.data.services.impl.jpa.repositories.JpaTagRepository;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
/**
* Tests for {@link DataAutoConfiguration}.
*
* @author tgianos
* @since 4.0.0
*/
@Disabled("For now this requires a lot of other auto configurations. Hard to isolate.")
class DataAutoConfigurationTest {
private ApplicationContextRunner contextRunner =
new ApplicationContextRunner()
.withConfiguration(
AutoConfigurations.of(
DataAutoConfiguration.class
)
);
/**
* All the expected beans exist.
*/
@Test
void expectedBeansExist() {
this.contextRunner.run(
context -> {
Assertions.assertThat(context).hasSingleBean(JpaApplicationRepository.class);
Assertions.assertThat(context).hasSingleBean(JpaClusterRepository.class);
Assertions.assertThat(context).hasSingleBean(JpaCommandRepository.class);
Assertions.assertThat(context).hasSingleBean(JpaCriterionRepository.class);
Assertions.assertThat(context).hasSingleBean(JpaFileRepository.class);
Assertions.assertThat(context).hasSingleBean(JpaJobRepository.class);
Assertions.assertThat(context).hasSingleBean(JpaTagRepository.class);
Assertions.assertThat(context).hasSingleBean(JpaRepositories.class);
Assertions.assertThat(context).hasSingleBean(DataServices.class);
Assertions.assertThat(context).hasSingleBean(JpaPersistenceServiceImpl.class);
}
);
}
}
| 2,474 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/data/package-info.java
|
/*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Tests for this package.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.spring.autoconfigure.data;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,475 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/aspects/AspectsAutoConfigurationTest.java
|
/*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.spring.autoconfigure.aspects;
import com.netflix.genie.web.aspects.DataServiceRetryAspect;
import com.netflix.genie.web.aspects.HealthCheckMetricsAspect;
import com.netflix.genie.web.aspects.SystemArchitecture;
import com.netflix.genie.web.properties.DataServiceRetryProperties;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.aop.aspectj.autoproxy.AspectJAwareAdvisorAutoProxyCreator;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Tests for {@link AspectsAutoConfiguration}.
*
* @author tgianos
* @since 4.0.0
*/
class AspectsAutoConfigurationTest {
private ApplicationContextRunner contextRunner =
new ApplicationContextRunner()
.withConfiguration(
AutoConfigurations.of(
AspectsAutoConfiguration.class
)
)
.withUserConfiguration(UserConfig.class);
/**
* Make sure all the expected beans are created by the auto configuration.
*/
@Test
void expectedBeansCreated() {
this.contextRunner.run(
context -> {
Assertions.assertThat(context).hasSingleBean(DataServiceRetryProperties.class);
Assertions.assertThat(context).hasSingleBean(AspectJAwareAdvisorAutoProxyCreator.class);
Assertions.assertThat(context).hasSingleBean(DataServiceRetryAspect.class);
Assertions.assertThat(context).hasSingleBean(HealthCheckMetricsAspect.class);
Assertions.assertThat(context).hasSingleBean(SystemArchitecture.class);
}
);
}
/**
* Dummy user configuration for tests.
*/
@Configuration
static class UserConfig {
/**
* Dummy meter registry.
*
* @return {@link SimpleMeterRegistry} instance
*/
@Bean
public MeterRegistry meterRegistry() {
return new SimpleMeterRegistry();
}
}
}
| 2,476 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/aspects/package-info.java
|
/*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Tests for this package.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.spring.autoconfigure.aspects;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,477 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/services/ServicesAutoConfigurationTest.java
|
/*
*
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.spring.autoconfigure.services;
import brave.Tracer;
import com.netflix.genie.common.internal.aws.s3.S3ClientFactory;
import com.netflix.genie.common.internal.tracing.brave.BraveTagAdapter;
import com.netflix.genie.common.internal.tracing.brave.BraveTracePropagator;
import com.netflix.genie.common.internal.tracing.brave.BraveTracingCleanup;
import com.netflix.genie.common.internal.tracing.brave.BraveTracingComponents;
import com.netflix.genie.common.internal.util.GenieHostInfo;
import com.netflix.genie.web.agent.services.AgentFileStreamService;
import com.netflix.genie.web.agent.services.AgentRoutingService;
import com.netflix.genie.web.data.services.DataServices;
import com.netflix.genie.web.properties.AttachmentServiceProperties;
import com.netflix.genie.web.properties.JobResolutionProperties;
import com.netflix.genie.web.properties.JobsActiveLimitProperties;
import com.netflix.genie.web.properties.JobsForwardingProperties;
import com.netflix.genie.web.properties.JobsLocationsProperties;
import com.netflix.genie.web.properties.JobsMemoryProperties;
import com.netflix.genie.web.properties.JobsProperties;
import com.netflix.genie.web.properties.JobsUsersProperties;
import com.netflix.genie.web.selectors.AgentLauncherSelector;
import com.netflix.genie.web.selectors.ClusterSelector;
import com.netflix.genie.web.selectors.CommandSelector;
import com.netflix.genie.web.services.ArchivedJobService;
import com.netflix.genie.web.services.AttachmentService;
import com.netflix.genie.web.services.JobDirectoryServerService;
import com.netflix.genie.web.services.JobLaunchService;
import com.netflix.genie.web.services.JobResolverService;
import com.netflix.genie.web.services.RequestForwardingService;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.client.RestTemplate;
import java.util.UUID;
/**
* Tests for {@link ServicesAutoConfiguration} class.
*
* @author mprimi
* @since 4.0.0
*/
class ServicesAutoConfigurationTest {
private final ApplicationContextRunner contextRunner =
new ApplicationContextRunner()
.withConfiguration(
AutoConfigurations.of(
ServicesAutoConfiguration.class
)
)
.withUserConfiguration(RequiredMockConfig.class);
@Test
void canCreateBeans() {
this.contextRunner.run(
context -> Assertions
.assertThat(context)
.hasSingleBean(JobsForwardingProperties.class)
.hasSingleBean(JobsLocationsProperties.class)
.hasSingleBean(JobsMemoryProperties.class)
.hasSingleBean(JobsUsersProperties.class)
.hasSingleBean(JobsActiveLimitProperties.class)
.hasSingleBean(AttachmentServiceProperties.class)
.hasSingleBean(JobsProperties.class)
.hasSingleBean(AttachmentService.class)
.hasSingleBean(JobResolverService.class)
.hasSingleBean(JobDirectoryServerService.class)
.hasSingleBean(JobLaunchService.class)
.hasSingleBean(ArchivedJobService.class)
.hasSingleBean(RequestForwardingService.class)
.hasSingleBean(JobResolutionProperties.class)
);
}
private static class RequiredMockConfig {
@Bean
MeterRegistry meterRegistry() {
return new SimpleMeterRegistry();
}
@Bean
ResourceLoader resourceLoader() {
return Mockito.mock(ResourceLoader.class);
}
@Bean
DataServices dataServices() {
return Mockito.mock(DataServices.class);
}
@Bean
AgentFileStreamService agentFileStreamService() {
return Mockito.mock(AgentFileStreamService.class);
}
@Bean
AgentRoutingService agentRoutingService() {
return Mockito.mock(AgentRoutingService.class);
}
@Bean
S3ClientFactory s3ClientFactory() {
return Mockito.mock(S3ClientFactory.class);
}
@Bean
CommandSelector commandSelector() {
return Mockito.mock(CommandSelector.class);
}
@Bean
ClusterSelector clusterSelector1() {
return Mockito.mock(ClusterSelector.class);
}
@Bean
ClusterSelector clusterSelector2() {
return Mockito.mock(ClusterSelector.class);
}
@Bean
AgentLauncherSelector agentLauncherSelector() {
return Mockito.mock(AgentLauncherSelector.class);
}
@Bean
GenieHostInfo genieHostInfo() {
return new GenieHostInfo(UUID.randomUUID().toString());
}
@Bean(name = "genieRestTemplate")
RestTemplate genieRestTemplate() {
return new RestTemplate();
}
@Bean
BraveTracingComponents tracingComponents() {
return new BraveTracingComponents(
Mockito.mock(Tracer.class),
Mockito.mock(BraveTracePropagator.class),
Mockito.mock(BraveTracingCleanup.class),
Mockito.mock(BraveTagAdapter.class)
);
}
}
}
| 2,478 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/services/package-info.java
|
/*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Tests for this package.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.spring.autoconfigure.services;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,479 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/selectors/SelectorsAutoConfigurationTest.java
|
/*
*
* Copyright 2020 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.spring.autoconfigure.selectors;
import com.netflix.genie.web.agent.launchers.AgentLauncher;
import com.netflix.genie.web.scripts.AgentLauncherSelectorManagedScript;
import com.netflix.genie.web.scripts.ClusterSelectorManagedScript;
import com.netflix.genie.web.scripts.CommandSelectorManagedScript;
import com.netflix.genie.web.selectors.AgentLauncherSelector;
import com.netflix.genie.web.selectors.ClusterSelector;
import com.netflix.genie.web.selectors.CommandSelector;
import com.netflix.genie.web.selectors.impl.RandomAgentLauncherSelectorImpl;
import com.netflix.genie.web.selectors.impl.RandomClusterSelectorImpl;
import com.netflix.genie.web.selectors.impl.RandomCommandSelectorImpl;
import com.netflix.genie.web.selectors.impl.ScriptAgentLauncherSelectorImpl;
import com.netflix.genie.web.selectors.impl.ScriptClusterSelectorImpl;
import com.netflix.genie.web.selectors.impl.ScriptCommandSelectorImpl;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered;
/**
* Tests for {@link SelectorsAutoConfiguration}.
*
* @author tgianos
* @since 4.0.0
*/
class SelectorsAutoConfigurationTest {
private ApplicationContextRunner contextRunner =
new ApplicationContextRunner()
.withConfiguration(
AutoConfigurations.of(
SelectorsAutoConfiguration.class
)
)
.withUserConfiguration(RegistryConfig.class, AgentLaunchersConfig.class);
@Test
void canCreateDefaultBeans() {
Assertions
.assertThat(SelectorsAutoConfiguration.SCRIPT_CLUSTER_SELECTOR_PRECEDENCE)
.isEqualTo(Ordered.LOWEST_PRECEDENCE - 50);
this.contextRunner.run(
context -> {
Assertions.assertThat(context).hasSingleBean(ClusterSelector.class);
Assertions.assertThat(context).hasSingleBean(RandomClusterSelectorImpl.class);
Assertions.assertThat(context).doesNotHaveBean(ScriptClusterSelectorImpl.class);
Assertions.assertThat(context).hasSingleBean(CommandSelector.class);
Assertions.assertThat(context).hasSingleBean(RandomCommandSelectorImpl.class);
Assertions.assertThat(context).doesNotHaveBean(ScriptCommandSelectorImpl.class);
Assertions.assertThat(context).hasSingleBean(AgentLauncherSelector.class);
Assertions.assertThat(context).hasSingleBean(RandomAgentLauncherSelectorImpl.class);
Assertions.assertThat(context).doesNotHaveBean(ScriptAgentLauncherSelectorImpl.class);
}
);
}
@Test
void canCreateConditionalBeans() {
this.contextRunner
.withUserConfiguration(ScriptsConfig.class)
.run(
context -> {
Assertions
.assertThat(context)
.hasSingleBean(RandomClusterSelectorImpl.class)
.hasSingleBean(ScriptClusterSelectorImpl.class)
.getBeans(ClusterSelector.class)
.hasSize(2); // No real easy way to test the order
Assertions.assertThat(context).hasSingleBean(CommandSelector.class);
Assertions.assertThat(context).doesNotHaveBean(RandomCommandSelectorImpl.class);
Assertions.assertThat(context).hasSingleBean(ScriptCommandSelectorImpl.class);
Assertions
.assertThat(context)
.doesNotHaveBean(RandomAgentLauncherSelectorImpl.class)
.hasSingleBean(ScriptAgentLauncherSelectorImpl.class);
}
);
}
@Test
void commandSelectorOverrideProvided() {
this.contextRunner
.withUserConfiguration(ScriptsConfig.class, OverridesConfig.class)
.run(
context -> {
Assertions.assertThat(context).hasSingleBean(CommandSelector.class);
Assertions.assertThat(context).doesNotHaveBean(RandomCommandSelectorImpl.class);
Assertions.assertThat(context).doesNotHaveBean(ScriptCommandSelectorImpl.class);
Assertions.assertThat(context).hasBean("customCommandSelector");
Assertions.assertThat(context).hasSingleBean(AgentLauncherSelector.class);
Assertions.assertThat(context).doesNotHaveBean(RandomAgentLauncherSelectorImpl.class);
Assertions.assertThat(context).doesNotHaveBean(ScriptAgentLauncherSelectorImpl.class);
Assertions.assertThat(context).hasBean("customAgentLauncherSelector");
}
);
}
/**
* Dummy config to create a {@link MeterRegistry} instance.
*/
private static class RegistryConfig {
/**
* Dummy meter registry.
*
* @return {@link SimpleMeterRegistry} instance
*/
@Bean
public MeterRegistry meterRegistry() {
return new SimpleMeterRegistry();
}
}
/**
* Dummy scripts configuration for tests.
*/
private static class ScriptsConfig {
/**
* Dummy script based cluster selector.
*/
@Bean
public ClusterSelectorManagedScript clusterSelectorScript() {
return Mockito.mock(ClusterSelectorManagedScript.class);
}
/**
* Dummy script based command selector.
*/
@Bean
public CommandSelectorManagedScript commandSelectorManagedScript() {
return Mockito.mock(CommandSelectorManagedScript.class);
}
/**
* Dummy script based agent launcher selector.
*/
@Bean
public AgentLauncherSelectorManagedScript agentLauncherSelectorManagedScript() {
return Mockito.mock(AgentLauncherSelectorManagedScript.class);
}
}
/**
* User provided command selector configuration.
*/
private static class OverridesConfig {
@Bean
public CommandSelector customCommandSelector() {
return Mockito.mock(CommandSelector.class);
}
@Bean
public AgentLauncherSelector customAgentLauncherSelector() {
return Mockito.mock(AgentLauncherSelector.class);
}
}
/**
* Agent launchers configuration.
*/
private static class AgentLaunchersConfig {
@Bean
public AgentLauncher launcher1() {
return Mockito.mock(AgentLauncher.class);
}
@Bean
public AgentLauncher launcher2() {
return Mockito.mock(AgentLauncher.class);
}
}
}
| 2,480 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/spring/autoconfigure/selectors/package-info.java
|
/*
*
* Copyright 2020 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Tests for this package.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.spring.autoconfigure.selectors;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,481 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/selectors
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/selectors/impl/RandomCommandSelectorImplTest.java
|
/*
*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.selectors.impl;
import com.google.common.collect.Sets;
import com.netflix.genie.common.internal.dtos.Command;
import com.netflix.genie.common.internal.dtos.JobRequest;
import com.netflix.genie.web.dtos.ResourceSelectionResult;
import com.netflix.genie.web.exceptions.checked.ResourceSelectionException;
import com.netflix.genie.web.selectors.CommandSelectionContext;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.util.Set;
import java.util.UUID;
/**
* Tests for {@link RandomCommandSelectorImpl}.
*
* @author tgianos
* @since 4.0.0
*/
class RandomCommandSelectorImplTest {
private RandomCommandSelectorImpl selector;
@BeforeEach
void setup() {
this.selector = new RandomCommandSelectorImpl();
}
@Test
void testValidCommandSet() throws ResourceSelectionException {
final Command command1 = Mockito.mock(Command.class);
final Command command2 = Mockito.mock(Command.class);
final Command command3 = Mockito.mock(Command.class);
final Set<Command> commands = Sets.newHashSet(command1, command2, command3);
final JobRequest jobRequest = Mockito.mock(JobRequest.class);
final String jobId = UUID.randomUUID().toString();
final CommandSelectionContext context = Mockito.mock(CommandSelectionContext.class);
Mockito.when(context.getResources()).thenReturn(commands);
Mockito.when(context.getJobId()).thenReturn(jobId);
Mockito.when(context.getJobRequest()).thenReturn(jobRequest);
for (int i = 0; i < 5; i++) {
final ResourceSelectionResult<Command> result = this.selector.select(context);
Assertions.assertThat(result).isNotNull();
Assertions.assertThat(result.getSelectorClass()).isEqualTo(RandomCommandSelectorImpl.class);
Assertions.assertThat(result.getSelectedResource()).isPresent().get().isIn(commands);
Assertions.assertThat(result.getSelectionRationale()).isPresent();
}
}
@Test
void testValidCommandSetOfOne() throws ResourceSelectionException {
final Command command = Mockito.mock(Command.class);
final CommandSelectionContext context = Mockito.mock(CommandSelectionContext.class);
Mockito.when(context.getResources()).thenReturn(Sets.newHashSet(command));
Mockito.when(context.getJobId()).thenReturn(UUID.randomUUID().toString());
Mockito.when(context.getJobRequest()).thenReturn(Mockito.mock(JobRequest.class));
final ResourceSelectionResult<Command> result = this.selector.select(context);
Assertions
.assertThat(result.getSelectedResource())
.isPresent()
.contains(command);
}
}
| 2,482 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/selectors
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/selectors/impl/RandomClusterSelectorImplTest.java
|
/*
*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.selectors.impl;
import com.google.common.collect.Sets;
import com.netflix.genie.common.internal.dtos.Cluster;
import com.netflix.genie.common.internal.dtos.JobRequest;
import com.netflix.genie.web.dtos.ResourceSelectionResult;
import com.netflix.genie.web.exceptions.checked.ResourceSelectionException;
import com.netflix.genie.web.selectors.ClusterSelectionContext;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.util.Set;
import java.util.UUID;
/**
* Test for {@link RandomClusterSelectorImpl}.
*
* @author tgianos
*/
class RandomClusterSelectorImplTest {
private RandomClusterSelectorImpl selector;
@BeforeEach
void setup() {
this.selector = new RandomClusterSelectorImpl();
}
@Test
void testValidClusterSet() throws ResourceSelectionException {
final Cluster cluster1 = Mockito.mock(Cluster.class);
final Cluster cluster2 = Mockito.mock(Cluster.class);
final Cluster cluster3 = Mockito.mock(Cluster.class);
final Set<Cluster> clusters = Sets.newHashSet(cluster1, cluster2, cluster3);
final JobRequest jobRequest = Mockito.mock(JobRequest.class);
final String jobId = UUID.randomUUID().toString();
final ClusterSelectionContext context = new ClusterSelectionContext(
jobId,
jobRequest,
true,
null,
clusters
);
for (int i = 0; i < 5; i++) {
final ResourceSelectionResult<Cluster> result = this.selector.select(context);
Assertions.assertThat(result).isNotNull();
Assertions.assertThat(result.getSelectorClass()).isEqualTo(RandomClusterSelectorImpl.class);
Assertions.assertThat(result.getSelectedResource()).isPresent().get().isIn(clusters);
Assertions.assertThat(result.getSelectionRationale()).isPresent();
}
}
@Test
void testValidClusterSetOfOne() throws ResourceSelectionException {
final Cluster cluster = Mockito.mock(Cluster.class);
final ClusterSelectionContext context = Mockito.mock(ClusterSelectionContext.class);
Mockito.when(context.getResources()).thenReturn(Sets.newHashSet(cluster));
Mockito.when(context.getClusters()).thenReturn(Sets.newHashSet(cluster));
Mockito.when(context.getJobId()).thenReturn(UUID.randomUUID().toString());
final ResourceSelectionResult<Cluster> result = this.selector.select(context);
Assertions
.assertThat(result.getSelectedResource())
.isPresent()
.contains(cluster);
}
}
| 2,483 |
0 |
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/selectors
|
Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/selectors/impl/package-info.java
|
/*
*
* Copyright 2020 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Tests for this package.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.selectors.impl;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,484 |
0 |
Create_ds/genie/genie-web/src/main/java/com/netflix/genie
|
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/package-info.java
|
/*
*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* All the Java classes to run the Genie web application.
*
* @author tgianos
* @since 3.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,485 |
0 |
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web
|
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/tasks/TasksCleanup.java
|
/*
*
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.tasks;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;
import javax.validation.constraints.NotNull;
/**
* Performs any cleanup when the system is shutting down.
*
* @author tgianos
* @since 3.0.0
*/
@Component
@Slf4j
public class TasksCleanup {
private final ThreadPoolTaskScheduler scheduler;
/**
* Constructor.
*
* @param scheduler The task scheduler for the system.
*/
@Autowired
public TasksCleanup(@Qualifier("genieTaskScheduler") @NotNull final ThreadPoolTaskScheduler scheduler) {
this.scheduler = scheduler;
}
/**
* When the spring context is about to close make sure we shutdown the thread pool and anything else we need to do.
*
* @param event The context closed event
*/
@EventListener
public void onShutdown(final ContextClosedEvent event) {
log.info("Shutting down the scheduler due to {}", event);
this.scheduler.shutdown();
}
}
| 2,486 |
0 |
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web
|
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/tasks/GenieTaskScheduleType.java
|
/*
*
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.tasks;
/**
* The enumeration values which a {@link GenieTask} can be be scheduled with.
*
* @author tgianos
* @since 3.0.0
*/
public enum GenieTaskScheduleType {
/**
* When you want your task scheduled using a {@link org.springframework.scheduling.Trigger}.
*/
TRIGGER,
/**
* When you want your task scheduled using a fixed rate in milliseconds.
*/
FIXED_RATE,
/**
* When you want your tasked scheduled at a fixed rate but held for a time after the last completion of the task.
*/
FIXED_DELAY
}
| 2,487 |
0 |
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web
|
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/tasks/GenieTask.java
|
/*
*
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.tasks;
import org.springframework.scheduling.Trigger;
/**
* Interface for any task that should run in the Genie system. Will be extended by more specific interfaces.
*
* @author tgianos
* @since 3.0.0
*/
public abstract class GenieTask implements Runnable {
/**
* Get the type of scheduling mechanism which should be used to schedule this task.
*
* @return The schedule type
*/
public abstract GenieTaskScheduleType getScheduleType();
/**
* Get the Trigger which this task should be scheduled with.
*
* @return The trigger
*/
public Trigger getTrigger() {
throw new UnsupportedOperationException("This task doesn't support being scheduled via Trigger.");
}
/**
* Get how long the system should wait between invoking the run() method of this task in milliseconds.
*
* @return The period to wait between invocations of run for this task
*/
public long getFixedRate() {
throw new UnsupportedOperationException("This task doesn't support being scheduled at a fixed rate.");
}
/**
* Get how long the system should wait between invoking the run() method of this task in milliseconds after the
* last successful run of the task.
*
* @return The time to delay between task completions
*/
public long getFixedDelay() {
throw new UnsupportedOperationException("This task doesn't support being scheduled at a fixed delay.");
}
}
| 2,488 |
0 |
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web
|
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/tasks/TaskUtils.java
|
/*
*
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.tasks;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
/**
* Utility methods used by various Genie tasks.
*
* @author tgianos
* @since 3.0.0
*/
public final class TaskUtils {
/**
* Protected constructor for utility class.
*/
protected TaskUtils() {
}
/**
* Get exactly midnight (00:00:00.000) UTC for the current day.
*
* @return 12 AM UTC.
*/
public static Instant getMidnightUTC() {
return ZonedDateTime.now(ZoneId.of("UTC")).withHour(0).withMinute(0).withSecond(0).withNano(0).toInstant();
}
}
| 2,489 |
0 |
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web
|
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/tasks/package-info.java
|
/*
*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Classes which Genie will run basically as cron jobs to do various impl.
*
* @author tgianos
* @since 3.0.0
*/
package com.netflix.genie.web.tasks;
| 2,490 |
0 |
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/tasks
|
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/tasks/leader/LeaderTask.java
|
/*
*
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.tasks.leader;
import com.netflix.genie.web.tasks.GenieTask;
import lombok.extern.slf4j.Slf4j;
/**
* Interface for any task that a node elected as the leader of a Genie cluster should run.
*
* @author tgianos
* @since 3.0.0
*/
@Slf4j
public abstract class LeaderTask extends GenieTask {
/**
* Any cleanup that needs to be performed when this task is stopped due to leadership being revoked.
*/
public void cleanup() {
log.info("Task cleanup called. Nothing to do.");
}
}
| 2,491 |
0 |
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/tasks
|
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/tasks/leader/ArchiveStatusCleanupTask.java
|
/*
*
* Copyright 2020 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.tasks.leader;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import com.netflix.genie.common.internal.dtos.ArchiveStatus;
import com.netflix.genie.common.internal.dtos.JobStatus;
import com.netflix.genie.web.agent.services.AgentRoutingService;
import com.netflix.genie.web.data.services.DataServices;
import com.netflix.genie.web.data.services.PersistenceService;
import com.netflix.genie.web.exceptions.checked.NotFoundException;
import com.netflix.genie.web.properties.ArchiveStatusCleanupProperties;
import com.netflix.genie.web.tasks.GenieTaskScheduleType;
import com.netflix.genie.web.util.MetricsUtils;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Tag;
import lombok.extern.slf4j.Slf4j;
import java.time.Instant;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* Leader task that find jobs whose archival status was left in 'PENDING' state.
* This can for example happen if the agent fails to update the server after successfully archiving.
* The logic is summarized as:
* If a job finished running more than N minutes ago, and the agent is disconnected and the archive status is PENDING,
* then set the archive status to UNKNOWN.
*
* @author mprimi
* @since 4.0.0
*/
@Slf4j
public class ArchiveStatusCleanupTask extends LeaderTask {
private static final String CLEAR_ARCHIVE_STATUS_COUNTER_NAME = "genie.jobs.archiveStatus.cleanup.counter";
private static final String CLEAR_ARCHIVE_STATUS_TIMER_NAME = "genie.tasks.archiveStatusCleanup.timer";
private static final Set<ArchiveStatus> PENDING_STATUS_SET = ImmutableSet.of(ArchiveStatus.PENDING);
private final PersistenceService persistenceService;
private final AgentRoutingService agentRoutingService;
private final ArchiveStatusCleanupProperties properties;
private final MeterRegistry registry;
/**
* Constructor.
*
* @param dataServices data services
* @param agentRoutingService agent routing service
* @param properties task properties
* @param registry metrics registry
*/
public ArchiveStatusCleanupTask(
final DataServices dataServices,
final AgentRoutingService agentRoutingService,
final ArchiveStatusCleanupProperties properties,
final MeterRegistry registry
) {
this.persistenceService = dataServices.getPersistenceService();
this.agentRoutingService = agentRoutingService;
this.properties = properties;
this.registry = registry;
}
/**
* {@inheritDoc}
*/
@Override
public void run() {
final Set<Tag> tags = Sets.newHashSet();
final long start = System.nanoTime();
try {
final Instant updatedThreshold = Instant.now().minus(this.properties.getGracePeriod());
final Set<String> jobIds = this.persistenceService.getJobsWithStatusAndArchiveStatusUpdatedBefore(
JobStatus.getFinishedStatuses(),
PENDING_STATUS_SET,
updatedThreshold
);
if (!jobIds.isEmpty()) {
log.debug("Found {} finished jobs with PENDING archive status", jobIds.size());
this.clearJobsArchiveStatus(jobIds);
}
MetricsUtils.addSuccessTags(tags);
} catch (Exception e) {
MetricsUtils.addFailureTagsWithException(tags, e);
log.error("Archive status cleanup task failed with exception: {}", e.getMessage(), e);
} finally {
final long taskDuration = System.nanoTime() - start;
registry.timer(CLEAR_ARCHIVE_STATUS_TIMER_NAME, tags).record(taskDuration, TimeUnit.NANOSECONDS);
}
}
private void clearJobsArchiveStatus(final Set<String> jobIds) {
for (final String jobId : jobIds) {
if (this.agentRoutingService.isAgentConnected(jobId)) {
log.debug("Agent for job {} is still connected and probably archiving", jobId);
} else {
log.warn("Marking job {} archive status to UNKNOWN", jobId);
final Set<Tag> tags = Sets.newHashSet();
try {
this.persistenceService.updateJobArchiveStatus(jobId, ArchiveStatus.UNKNOWN);
MetricsUtils.addSuccessTags(tags);
} catch (NotFoundException e) {
log.error("Tried to update a job that does not exist: {}", jobId);
MetricsUtils.addFailureTagsWithException(tags, e);
} finally {
registry.counter(CLEAR_ARCHIVE_STATUS_COUNTER_NAME, tags).increment();
}
}
}
}
/**
* {@inheritDoc}
*/
@Override
public GenieTaskScheduleType getScheduleType() {
return GenieTaskScheduleType.FIXED_RATE;
}
/**
* {@inheritDoc}
*/
@Override
public long getFixedRate() {
return this.properties.getCheckInterval().toMillis();
}
}
| 2,492 |
0 |
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/tasks
|
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/tasks/leader/LeaderTasksCoordinator.java
|
/*
*
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.tasks.leader;
import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.integration.leader.event.AbstractLeaderEvent;
import org.springframework.integration.leader.event.OnGrantedEvent;
import org.springframework.integration.leader.event.OnRevokedEvent;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.Trigger;
import javax.annotation.PreDestroy;
import java.util.Collection;
import java.util.Set;
import java.util.concurrent.ScheduledFuture;
/**
* Class which handles coordinating leadership related tasks. Listens for leadership grant and revoke events and starts
* tasks associated with being the cluster leader.
*
* @author tgianos
* @since 3.0.0
*/
@Slf4j
public class LeaderTasksCoordinator {
private final Set<LeaderTask> tasks;
private final Set<ScheduledFuture<?>> futures;
private final TaskScheduler taskScheduler;
private boolean isRunning;
/**
* Constructor.
*
* @param taskScheduler The task executor to use.
* @param tasks The leadership tasks to run
*/
public LeaderTasksCoordinator(final TaskScheduler taskScheduler, final Collection<LeaderTask> tasks) {
this.futures = Sets.newHashSet();
this.taskScheduler = taskScheduler;
this.isRunning = false;
this.tasks = Sets.newHashSet();
if (tasks != null) {
this.tasks.addAll(tasks);
}
}
/**
* Make sure any threads are taken care of before this object is destroyed.
*/
@PreDestroy
public void preDestroy() {
this.cancelTasks();
}
/**
* Leadership event listener. Starts and stop processes when this Genie node is elected the leader of the cluster.
* <p>
* Synchronized to ensure no race conditions between threads trying to start and stop leadership tasks.
*
* @param leaderEvent The leader grant or revoke event
* @see org.springframework.integration.leader.event.OnGrantedEvent
* @see org.springframework.integration.leader.event.OnRevokedEvent
*/
@EventListener
public synchronized void onLeaderEvent(final AbstractLeaderEvent leaderEvent) {
if (leaderEvent instanceof OnGrantedEvent) {
if (this.isRunning) {
return;
}
log.info("Leadership granted.");
this.isRunning = true;
this.tasks.forEach(
task -> {
switch (task.getScheduleType()) {
case TRIGGER:
final Trigger trigger = task.getTrigger();
log.info(
"Scheduling leadership task {} to run with trigger {}",
task.getClass().getCanonicalName(),
trigger
);
this.futures.add(this.taskScheduler.schedule(task, trigger));
break;
case FIXED_RATE:
final long rate = task.getFixedRate();
log.info(
"Scheduling leadership task {} to run every {} second(s)",
task.getClass().getCanonicalName(),
rate / 1000.0
);
this.futures.add(this.taskScheduler.scheduleAtFixedRate(task, rate));
break;
case FIXED_DELAY:
final long delay = task.getFixedDelay();
log.info(
"Scheduling leadership task {} to run at a fixed delay of every {} second(s)",
task.getClass().getCanonicalName(),
delay / 1000.0
);
this.futures.add(this.taskScheduler.scheduleWithFixedDelay(task, delay));
break;
default:
log.error("Unknown Genie task type {}", task.getScheduleType());
}
}
);
} else if (leaderEvent instanceof OnRevokedEvent) {
if (!this.isRunning) {
return;
}
log.info("Leadership revoked.");
this.isRunning = false;
this.cancelTasks();
} else {
log.warn("Unknown leadership event {}. Ignoring.", leaderEvent);
}
}
private void cancelTasks() {
for (final ScheduledFuture<?> future : this.futures) {
log.info("Attempting to cancel thread {}", future);
if (future.cancel(true)) {
log.info("Successfully cancelled.");
} else {
log.info("Failed to cancel.");
}
}
// Clear out the tasks
this.futures.clear();
this.tasks.forEach(LeaderTask::cleanup);
}
}
| 2,493 |
0 |
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/tasks
|
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/tasks/leader/AgentJobCleanupTask.java
|
/*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.tasks.leader;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.netflix.genie.common.internal.dtos.ArchiveStatus;
import com.netflix.genie.common.internal.dtos.JobStatus;
import com.netflix.genie.common.internal.exceptions.unchecked.GenieInvalidStatusException;
import com.netflix.genie.web.agent.services.AgentRoutingService;
import com.netflix.genie.web.data.services.DataServices;
import com.netflix.genie.web.data.services.PersistenceService;
import com.netflix.genie.web.exceptions.checked.NotFoundException;
import com.netflix.genie.web.properties.AgentCleanupProperties;
import com.netflix.genie.web.tasks.GenieTaskScheduleType;
import com.netflix.genie.web.util.MetricsUtils;
import io.micrometer.core.instrument.MeterRegistry;
import lombok.extern.slf4j.Slf4j;
import java.time.Instant;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
/**
* Leader task that cleans up jobs whose agent crashed or disconnected.
*
* @author mprimi
* @since 4.0.0
*/
@Slf4j
public class AgentJobCleanupTask extends LeaderTask {
private static final String AWOL_STATUS_MESSAGE = "Agent AWOL for too long";
private static final String NEVER_CLAIMED_STATUS_MESSAGE = "No agent claimed the job for too long";
private static final String TERMINATED_COUNTER_METRIC_NAME = "genie.jobs.agentDisconnected.terminated.counter";
private static final String DISCONNECTED_GAUGE_METRIC_NAME = "genie.jobs.agentDisconnected.gauge";
private final Map<String, Instant> awolJobsMap;
private final PersistenceService persistenceService;
private final AgentCleanupProperties properties;
private final MeterRegistry registry;
private final AgentRoutingService agentRoutingService;
/**
* Constructor.
*
* @param dataServices The {@link DataServices} encapsulation instance to use
* @param properties the task properties
* @param registry the metrics registry
* @param agentRoutingService the agent routing service
*/
public AgentJobCleanupTask(
final DataServices dataServices,
final AgentCleanupProperties properties,
final MeterRegistry registry,
final AgentRoutingService agentRoutingService
) {
this.persistenceService = dataServices.getPersistenceService();
this.properties = properties;
this.registry = registry;
this.agentRoutingService = agentRoutingService;
this.awolJobsMap = Maps.newConcurrentMap();
// Auto-publish number of jobs tracked for shutdown due to agent not being connected.
this.registry.gaugeMapSize(
DISCONNECTED_GAUGE_METRIC_NAME,
Sets.newHashSet(),
this.awolJobsMap
);
}
/**
* {@inheritDoc}
*/
@Override
public void run() {
// Get agent jobs that in active status
final Set<String> activeAgentJobIds = this.persistenceService.getActiveJobs();
// Get agent jobs that in ACCEPTED status (i.e. waiting for agent to start)
final Set<String> acceptedAgentJobIds = this.persistenceService.getUnclaimedJobs();
// Filter out jobs whose agent is connected
final Set<String> currentlyAwolJobsIds = activeAgentJobIds
.stream()
.filter(jobId -> !this.agentRoutingService.isAgentConnected(jobId))
.collect(Collectors.toSet());
// Purge records if corresponding agent is now connected
this.awolJobsMap.entrySet().removeIf(awolJobEntry -> !currentlyAwolJobsIds.contains(awolJobEntry.getKey()));
final Instant now = Instant.now();
// Add records for any agent that was not previously AWOL
currentlyAwolJobsIds.forEach(jobId -> this.awolJobsMap.putIfAbsent(jobId, now));
// Iterate over jobs whose agent is currently AWOL
for (final Map.Entry<String, Instant> entry : this.awolJobsMap.entrySet()) {
final String awolJobId = entry.getKey();
final Instant awolJobFirstSeen = entry.getValue();
final boolean jobWasClaimed = !acceptedAgentJobIds.contains(awolJobId);
final Instant claimDeadline = awolJobFirstSeen.plus(this.properties.getLaunchTimeLimit());
final Instant reconnectDeadline = awolJobFirstSeen.plus(this.properties.getReconnectTimeLimit());
if (!jobWasClaimed && now.isBefore(claimDeadline)) {
log.debug("Job {} agent still pending agent start/claim", awolJobId);
} else if (jobWasClaimed && now.isBefore(reconnectDeadline)) {
log.debug("Job {} agent still disconnected", awolJobId);
} else {
log.warn("Job {} agent AWOL for too long, marking failed", awolJobId);
try {
final JobStatus currentStatus = this.persistenceService.getJobStatus(awolJobId);
final ArchiveStatus archiveStatus = this.persistenceService.getJobArchiveStatus(awolJobId);
// Update job archive status
if (archiveStatus == ArchiveStatus.PENDING) {
this.persistenceService.updateJobArchiveStatus(
awolJobId,
jobWasClaimed ? ArchiveStatus.UNKNOWN : ArchiveStatus.FAILED
);
}
// Mark the job as failed
this.persistenceService.updateJobStatus(
awolJobId,
currentStatus,
JobStatus.FAILED,
jobWasClaimed ? AWOL_STATUS_MESSAGE : NEVER_CLAIMED_STATUS_MESSAGE
);
// If marking as failed succeeded, remove it from the map
this.awolJobsMap.remove(awolJobId);
// Increment counter, tag as successful
this.registry.counter(
TERMINATED_COUNTER_METRIC_NAME,
MetricsUtils.newSuccessTagsSet()
).increment();
} catch (NotFoundException | GenieInvalidStatusException e) {
log.warn("Failed to mark AWOL job {} as failed: ", awolJobId, e);
// Increment counter, tag as failure
this.registry.counter(
TERMINATED_COUNTER_METRIC_NAME,
MetricsUtils.newFailureTagsSetForException(e)
).increment();
}
}
}
}
/**
* {@inheritDoc}
*/
@Override
public void cleanup() {
// Throw away all deadlines
this.awolJobsMap.clear();
}
/**
* {@inheritDoc}
*/
@Override
public GenieTaskScheduleType getScheduleType() {
return GenieTaskScheduleType.FIXED_RATE;
}
/**
* {@inheritDoc}
*/
@Override
public long getFixedRate() {
return this.properties.getRefreshInterval().toMillis();
}
}
| 2,494 |
0 |
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/tasks
|
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/tasks/leader/UserMetricsTask.java
|
/*
*
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.tasks.leader;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.common.util.concurrent.AtomicDouble;
import com.netflix.genie.common.dto.UserResourcesSummary;
import com.netflix.genie.common.internal.dtos.JobStatus;
import com.netflix.genie.web.data.services.DataServices;
import com.netflix.genie.web.data.services.PersistenceService;
import com.netflix.genie.web.properties.UserMetricsProperties;
import com.netflix.genie.web.tasks.GenieTaskScheduleType;
import com.netflix.genie.web.util.MetricsConstants;
import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.MeterRegistry;
import lombok.extern.slf4j.Slf4j;
import java.util.Map;
import java.util.Set;
/**
* A task which publishes user metrics.
*
* @author mprimi
* @since 4.0.0
*/
@Slf4j
public class UserMetricsTask extends LeaderTask {
private static final String USER_ACTIVE_JOBS_METRIC_NAME = "genie.user.active-jobs.gauge";
private static final String USER_ACTIVE_MEMORY_METRIC_NAME = "genie.user.active-memory.gauge";
private static final String USER_ACTIVE_USERS_METRIC_NAME = "genie.user.active-users.gauge";
private static final UserResourcesRecord USER_RECORD_PLACEHOLDER = new UserResourcesRecord("nobody");
private final MeterRegistry registry;
private final PersistenceService persistenceService;
private final UserMetricsProperties userMetricsProperties;
private final Map<String, UserResourcesRecord> userResourcesRecordMap = Maps.newHashMap();
private final AtomicDouble activeUsersCount;
/**
* Constructor.
*
* @param registry the metrics registry
* @param dataServices The {@link DataServices} instance to use
* @param userMetricsProperties the properties that configure this task
*/
public UserMetricsTask(
final MeterRegistry registry,
final DataServices dataServices,
final UserMetricsProperties userMetricsProperties
) {
this.registry = registry;
this.persistenceService = dataServices.getPersistenceService();
this.userMetricsProperties = userMetricsProperties;
this.activeUsersCount = new AtomicDouble(Double.NaN);
// Register gauge for count of distinct users with active jobs.
Gauge.builder(USER_ACTIVE_USERS_METRIC_NAME, this::getUsersCount)
.register(registry);
}
/**
* {@inheritDoc}
*/
@Override
public GenieTaskScheduleType getScheduleType() {
return GenieTaskScheduleType.FIXED_RATE;
}
/**
* {@inheritDoc}
*/
@Override
public long getFixedRate() {
return this.userMetricsProperties.getRefreshInterval();
}
/**
* {@inheritDoc}
*/
@Override
public void run() {
log.debug("Publishing user metrics");
// For now just report the API jobs as they're using resources on Genie web nodes
// Get us unblocked for now on agent migration but in future we may want to change this to further dice or
// combine reports by CLI vs. API
final Map<String, UserResourcesSummary> summaries = this.persistenceService.getUserResourcesSummaries(
JobStatus.getActiveStatuses(),
true
);
// Update number of active users
log.debug("Number of users with active jobs: {}", summaries.size());
this.activeUsersCount.set(summaries.size());
// Track users who previously had jobs but no longer do
final Set<String> usersToReset = Sets.newHashSet(this.userResourcesRecordMap.keySet());
usersToReset.removeAll(summaries.keySet());
for (final String user : usersToReset) {
// Remove user. If gauge is polled, it'll return NaN
this.userResourcesRecordMap.remove(user);
}
// Update existing user metrics
for (final UserResourcesSummary userResourcesSummary : summaries.values()) {
final String user = userResourcesSummary.getUser();
final long jobs = userResourcesSummary.getRunningJobsCount();
final long memory = userResourcesSummary.getUsedMemory();
log.debug("User {}: {} jobs running, using {}MB", user, jobs, memory);
this.userResourcesRecordMap.computeIfAbsent(
userResourcesSummary.getUser(),
userName -> {
// Register gauges this user user.
// Gauge creation is idempotent so it doesn't matter if the user is new or seen before.
// Registry holds a reference to the gauge so no need to save it.
Gauge.builder(
USER_ACTIVE_JOBS_METRIC_NAME,
() -> this.getUserJobCount(userName)
)
.tags(MetricsConstants.TagKeys.USER, userName)
.register(registry);
Gauge.builder(
USER_ACTIVE_MEMORY_METRIC_NAME,
() -> this.getUserMemoryAmount(userName)
)
.tags(MetricsConstants.TagKeys.USER, userName)
.register(registry);
return new UserResourcesRecord(userName);
}
).update(jobs, memory);
}
log.debug("Done publishing user metrics");
}
/**
* {@inheritDoc}
*/
@Override
public void cleanup() {
log.debug("Cleaning up user metrics publishing");
// Reset all users
this.userResourcesRecordMap.clear();
// Reset active users count
this.activeUsersCount.set(Double.NaN);
}
private Number getUserJobCount(final String userName) {
final UserResourcesRecord record = this.userResourcesRecordMap.getOrDefault(userName, USER_RECORD_PLACEHOLDER);
final double jobCount = record.jobCount.get();
log.debug("Current jobs count for user '{}' is {}", userName, (long) jobCount);
return jobCount;
}
private Number getUserMemoryAmount(final String userName) {
final UserResourcesRecord record = this.userResourcesRecordMap.getOrDefault(userName, USER_RECORD_PLACEHOLDER);
final double memoryAmount = record.memoryAmount.get();
log.debug("Current memory amount for user '{}' is {}MB", userName, (long) memoryAmount);
return memoryAmount;
}
private Number getUsersCount() {
return activeUsersCount.get();
}
private static class UserResourcesRecord {
private final String userName;
private final AtomicDouble jobCount = new AtomicDouble(Double.NaN);
private final AtomicDouble memoryAmount = new AtomicDouble(Double.NaN);
UserResourcesRecord(
final String userName
) {
this.userName = userName;
}
void update(final long runningJobsCount, final long usedMemory) {
log.debug(
"Updating usage of user '{}': {} jobs totalling {}MB",
this.userName,
runningJobsCount,
usedMemory
);
this.jobCount.set(runningJobsCount);
this.memoryAmount.set(usedMemory);
}
}
}
| 2,495 |
0 |
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/tasks
|
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/tasks/leader/LocalLeader.java
|
/*
*
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.tasks.leader;
import com.netflix.genie.web.events.GenieEventBus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.integration.leader.event.OnGrantedEvent;
import org.springframework.integration.leader.event.OnRevokedEvent;
import javax.annotation.concurrent.ThreadSafe;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* A class to control leadership activities when remote leadership isn't enabled and this node has been forcibly
* elected as the leader.
*
* @author tgianos
* @since 3.0.0
*/
@Slf4j
@ThreadSafe
public class LocalLeader {
private final GenieEventBus genieEventBus;
private final boolean isLeader;
private final AtomicBoolean isRunning;
/**
* Constructor.
*
* @param genieEventBus The spring application event publisher to use to invoke that this node is a leader
* @param isLeader Whether this node should be the leader or not. Should only be one in a cluster but not
* enforced by Genie at this time
*/
public LocalLeader(final GenieEventBus genieEventBus, final boolean isLeader) {
this.genieEventBus = genieEventBus;
this.isLeader = isLeader;
this.isRunning = new AtomicBoolean(false);
if (this.isLeader) {
log.info("Constructing LocalLeader. This node IS the leader.");
} else {
log.info("Constructing LocalLeader. This node IS NOT the leader.");
}
}
/**
* Auto-start once application is up and running.
*
* @param event The Spring Boot application ready event to startup on
*/
@EventListener
public void startLeadership(final ContextRefreshedEvent event) {
log.debug("Starting Leadership due to {}", event);
this.start();
}
/**
* Auto-stop once application is shutting down.
*
* @param event The application context closing event
*/
@EventListener
public void stopLeadership(final ContextClosedEvent event) {
log.debug("Stopping Leadership due to {}", event);
this.stop();
}
/**
* If configured to be leader and previously started, deactivate and send a leadership lost notification.
* NOOP if not running or if this node is not configured to be leader.
*/
public void stop() {
if (this.isRunning.compareAndSet(true, false) && this.isLeader) {
log.info("Stopping Leadership");
this.genieEventBus.publishSynchronousEvent(new OnRevokedEvent(this, null, "leader"));
}
}
/**
* If configured to be leader, activate and send a leadership acquired notification.
* NOOP if already running or if this node is not configured to be leader.
*/
public void start() {
if (this.isRunning.compareAndSet(false, true) && this.isLeader) {
log.debug("Starting Leadership");
this.genieEventBus.publishSynchronousEvent(new OnGrantedEvent(this, null, "leader"));
}
}
/**
* Whether this module is active.
*
* @return true if {@link LocalLeader#start()} was called.
*/
public boolean isRunning() {
return this.isRunning.get();
}
/**
* Whether local node is leader.
*
* @return true if this module is active and the node is configured to be leader
*/
public boolean isLeader() {
return this.isRunning() && this.isLeader;
}
}
| 2,496 |
0 |
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/tasks
|
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/tasks/leader/DatabaseCleanupTask.java
|
/*
*
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.tasks.leader;
import com.google.common.collect.Sets;
import com.netflix.genie.common.internal.dtos.ClusterStatus;
import com.netflix.genie.common.internal.dtos.CommandStatus;
import com.netflix.genie.common.internal.dtos.JobStatus;
import com.netflix.genie.common.internal.jobs.JobConstants;
import com.netflix.genie.web.data.services.DataServices;
import com.netflix.genie.web.data.services.PersistenceService;
import com.netflix.genie.web.properties.DatabaseCleanupProperties;
import com.netflix.genie.web.tasks.GenieTaskScheduleType;
import com.netflix.genie.web.tasks.TaskUtils;
import com.netflix.genie.web.util.MetricsUtils;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.support.CronTrigger;
import javax.validation.constraints.NotNull;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.EnumSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
/**
* A {@link LeaderTask} which will clean up the database of old records if desired.
*
* @author tgianos
* @since 3.0.0
*/
// TODO: The intention of this class is clear, it is to have the leader trigger a database cleanup action periodically
// at system administrators discretion. The issue here is that this current implementation bleeds a lot of
// details about the underlying implementation into this class. If someone were to re-implement the persistence
// tier using a different underlying technology it is unlikely they would expose tags or files as separate
// fields. Their existence here is merely a side effect of our relational database implementation. The proper
// thing to do here seems to be to have this task merely kick off a single API call into the persistence tier
// and then that tier does what it thinks is best. I (TJG) might have tackled this as part of the large
// persistence tier refactoring in 4/2020 however looking at this class it has a lot of details that need to be
// moved properly (metrics, logging, properties) that it looks like it's own larger initiative that I don't have
// time to tackle right now. I do think it should be done though so I'm leaving this large note so as not to
// forget and hopefully come back to it once there is some time. - TJG 4/21/2020
@Slf4j
public class DatabaseCleanupTask extends LeaderTask {
private static final String DATABASE_CLEANUP_DURATION_TIMER_NAME = "genie.tasks.databaseCleanup.duration.timer";
private static final String APPLICATION_DELETION_TIMER = "genie.tasks.databaseCleanup.applicationDeletion.timer";
private static final String CLUSTER_DELETION_TIMER = "genie.tasks.databaseCleanup.clusterDeletion.timer";
private static final String COMMAND_DEACTIVATION_TIMER = "genie.tasks.databaseCleanup.commandDeactivation.timer";
private static final String COMMAND_DELETION_TIMER = "genie.tasks.databaseCleanup.commandDeletion.timer";
private static final String FILE_DELETION_TIMER = "genie.tasks.databaseCleanup.fileDeletion.timer";
private static final String TAG_DELETION_TIMER = "genie.tasks.databaseCleanup.tagDeletion.timer";
// TODO: May want to make this a property
private static final Set<CommandStatus> TO_DEACTIVATE_COMMAND_STATUSES = EnumSet.of(
CommandStatus.DEPRECATED,
CommandStatus.ACTIVE
);
// TODO: May want to make this a property
private static final Set<CommandStatus> TO_DELETE_COMMAND_STATUSES = EnumSet.of(CommandStatus.INACTIVE);
// TODO: May want to make this a property. Currently this maintains consistent behavior with before but it would
// be nice to add OUT_OF_SERVICE
private static final Set<ClusterStatus> TO_DELETE_CLUSTER_STATUSES = EnumSet.of(ClusterStatus.TERMINATED);
private final DatabaseCleanupProperties cleanupProperties;
private final Environment environment;
private final PersistenceService persistenceService;
private final MeterRegistry registry;
private final AtomicLong numDeletedJobs;
private final AtomicLong numDeletedClusters;
private final AtomicLong numDeactivatedCommands;
private final AtomicLong numDeletedCommands;
private final AtomicLong numDeletedApplications;
private final AtomicLong numDeletedTags;
private final AtomicLong numDeletedFiles;
/**
* Constructor.
*
* @param cleanupProperties The properties to use to configure this task
* @param environment The application environment to pull properties from
* @param dataServices The {@link DataServices} encapsulation instance to use
* @param registry The metrics registry
*/
public DatabaseCleanupTask(
@NotNull final DatabaseCleanupProperties cleanupProperties,
@NotNull final Environment environment,
@NotNull final DataServices dataServices,
@NotNull final MeterRegistry registry
) {
this.registry = registry;
this.cleanupProperties = cleanupProperties;
this.environment = environment;
this.persistenceService = dataServices.getPersistenceService();
this.numDeletedJobs = this.registry.gauge(
"genie.tasks.databaseCleanup.numDeletedJobs.gauge",
new AtomicLong()
);
this.numDeletedClusters = this.registry.gauge(
"genie.tasks.databaseCleanup.numDeletedClusters.gauge",
new AtomicLong()
);
this.numDeactivatedCommands = this.registry.gauge(
"genie.tasks.databaseCleanup.numDeactivatedCommands.gauge",
new AtomicLong()
);
this.numDeletedCommands = this.registry.gauge(
"genie.tasks.databaseCleanup.numDeletedCommands.gauge",
new AtomicLong()
);
this.numDeletedApplications = this.registry.gauge(
"genie.tasks.databaseCleanup.numDeletedApplications.gauge",
new AtomicLong()
);
this.numDeletedTags = this.registry.gauge(
"genie.tasks.databaseCleanup.numDeletedTags.gauge",
new AtomicLong()
);
this.numDeletedFiles = this.registry.gauge(
"genie.tasks.databaseCleanup.numDeletedFiles.gauge",
new AtomicLong()
);
}
/**
* {@inheritDoc}
*/
@Override
public GenieTaskScheduleType getScheduleType() {
return GenieTaskScheduleType.TRIGGER;
}
/**
* {@inheritDoc}
*/
@Override
public Trigger getTrigger() {
final String expression = this.environment.getProperty(
DatabaseCleanupProperties.EXPRESSION_PROPERTY,
String.class,
this.cleanupProperties.getExpression()
);
return new CronTrigger(expression, JobConstants.UTC);
}
/**
* Clean out database based on date.
*/
@Override
public void run() {
final long start = System.nanoTime();
final Instant runtime = Instant.now();
final Set<Tag> tags = Sets.newHashSet();
try {
this.deleteJobs();
// Get now - 1 hour to avoid deleting references that were created as part of new resources recently
final Instant creationThreshold = runtime.minus(1L, ChronoUnit.HOURS);
this.deleteClusters(creationThreshold);
this.deleteCommands(creationThreshold);
this.deactivateCommands(runtime);
this.deleteApplications(creationThreshold);
this.deleteFiles(creationThreshold);
this.deleteTags(creationThreshold);
MetricsUtils.addSuccessTags(tags);
} catch (final Throwable t) {
MetricsUtils.addFailureTagsWithException(tags, t);
throw t;
} finally {
this.registry
.timer(DATABASE_CLEANUP_DURATION_TIMER_NAME, tags)
.record(System.nanoTime() - start, TimeUnit.NANOSECONDS);
}
}
/**
* {@inheritDoc}
*/
@Override
public void cleanup() {
this.numDeletedJobs.set(0L);
this.numDeletedClusters.set(0L);
this.numDeactivatedCommands.set(0L);
this.numDeletedCommands.set(0L);
this.numDeletedApplications.set(0L);
this.numDeletedTags.set(0L);
this.numDeletedFiles.set(0L);
}
/*
* Delete jobs that are older than the retention threshold and are complete
*/
private void deleteJobs() {
final boolean skipJobs = this.environment.getProperty(
DatabaseCleanupProperties.JobDatabaseCleanupProperties.SKIP_PROPERTY,
Boolean.class,
this.cleanupProperties.getJobCleanup().isSkip()
);
if (skipJobs) {
log.info("Skipping job cleanup");
this.numDeletedJobs.set(0);
} else {
// TODO: Maybe we shouldn't reset it to midnight no matter what... just go with runtime minus something
final Instant midnightUTC = TaskUtils.getMidnightUTC();
final Instant retentionLimit = midnightUTC.minus(
this.environment.getProperty(
DatabaseCleanupProperties.JobDatabaseCleanupProperties.JOB_RETENTION_PROPERTY,
Integer.class,
this.cleanupProperties.getJobCleanup().getRetention()
),
ChronoUnit.DAYS
);
final int batchSize = this.environment.getProperty(
DatabaseCleanupProperties.JobDatabaseCleanupProperties.PAGE_SIZE_PROPERTY,
Integer.class,
this.cleanupProperties.getJobCleanup().getPageSize()
);
log.info(
"Attempting to delete jobs from before {} in batches of {} jobs per iteration",
retentionLimit,
batchSize
);
long numDeletedJobsInBatch;
long totalDeletedJobs = 0L;
do {
numDeletedJobsInBatch = this.persistenceService.deleteJobsCreatedBefore(
retentionLimit,
JobStatus.getActiveStatuses(),
batchSize
);
totalDeletedJobs += numDeletedJobsInBatch;
} while (numDeletedJobsInBatch != 0);
log.info(
"Deleted {} jobs",
totalDeletedJobs
);
this.numDeletedJobs.set(totalDeletedJobs);
}
}
/*
* Delete all clusters that are marked terminated and aren't attached to any jobs after jobs were deleted.
*/
private void deleteClusters(final Instant creationThreshold) {
final long startTime = System.nanoTime();
final Set<Tag> tags = Sets.newHashSet();
try {
final boolean skipClusters = this.environment.getProperty(
DatabaseCleanupProperties.ClusterDatabaseCleanupProperties.SKIP_PROPERTY,
Boolean.class,
this.cleanupProperties.getClusterCleanup().isSkip()
);
if (skipClusters) {
log.info("Skipping clusters cleanup");
this.numDeletedClusters.set(0);
} else {
final int batchSize = this.environment.getProperty(
DatabaseCleanupProperties.BATCH_SIZE_PROPERTY,
Integer.class,
this.cleanupProperties.getBatchSize()
);
log.info(
"Attempting to delete unused clusters from before {} in batches of {}",
creationThreshold,
batchSize
);
long deleted;
long totalDeleted = 0L;
do {
deleted = this.persistenceService.deleteUnusedClusters(
TO_DELETE_CLUSTER_STATUSES,
creationThreshold,
batchSize
);
totalDeleted += deleted;
} while (deleted > 0);
log.info(
"Deleted {} clusters that were in one of {} states, were created before {} and weren't "
+ " attached to any jobs",
totalDeleted,
TO_DELETE_CLUSTER_STATUSES,
creationThreshold
);
this.numDeletedClusters.set(totalDeleted);
}
} catch (final Exception e) {
log.error("Unable to delete clusters from database", e);
MetricsUtils.addFailureTagsWithException(tags, e);
} finally {
this.registry
.timer(CLUSTER_DELETION_TIMER, tags)
.record(System.nanoTime() - startTime, TimeUnit.NANOSECONDS);
}
}
private void deleteFiles(final Instant creationThreshold) {
final long startTime = System.nanoTime();
final Set<Tag> tags = Sets.newHashSet();
try {
final boolean skipFiles = this.environment.getProperty(
DatabaseCleanupProperties.FileDatabaseCleanupProperties.SKIP_PROPERTY,
Boolean.class,
this.cleanupProperties.getFileCleanup().isSkip()
);
if (skipFiles) {
log.info("Skipping files cleanup");
this.numDeletedFiles.set(0);
} else {
final int batchSize = this.environment.getProperty(
DatabaseCleanupProperties.BATCH_SIZE_PROPERTY,
Integer.class,
this.cleanupProperties.getBatchSize()
);
final long rollingWindowHours = this.environment.getProperty(
DatabaseCleanupProperties.FileDatabaseCleanupProperties.ROLLING_WINDOW_HOURS_PROPERTY,
Integer.class,
this.cleanupProperties.getFileCleanup().getRollingWindowHours()
);
final long batchDaysWithin = this.environment.getProperty(
DatabaseCleanupProperties.FileDatabaseCleanupProperties.BATCH_DAYS_WITHIN_PROPERTY,
Integer.class,
this.cleanupProperties.getFileCleanup().getBatchDaysWithin()
);
log.info(
"Attempting to delete unused files from before {} in batches of {}",
creationThreshold,
batchSize
);
long totalDeleted = 0L;
Instant upperBound = creationThreshold;
Instant lowerBound = creationThreshold.minus(rollingWindowHours, ChronoUnit.HOURS);
final Instant batchLowerBound = creationThreshold.minus(batchDaysWithin, ChronoUnit.DAYS);
while (upperBound.isAfter(batchLowerBound)) {
totalDeleted += deleteUnusedFilesBetween(lowerBound, upperBound, batchSize);
upperBound = lowerBound;
lowerBound = lowerBound.minus(rollingWindowHours, ChronoUnit.HOURS);
}
// do a final deletion of everything < batchLowerBound
totalDeleted += deleteUnusedFilesBetween(Instant.EPOCH, upperBound, batchSize);
log.info(
"Deleted {} files that were unused by any resource and created before {}",
totalDeleted,
creationThreshold
);
this.numDeletedFiles.set(totalDeleted);
}
} catch (final Exception e) {
log.error("Unable to delete files from database", e);
MetricsUtils.addFailureTagsWithException(tags, e);
} finally {
this.registry
.timer(FILE_DELETION_TIMER, tags)
.record(System.nanoTime() - startTime, TimeUnit.NANOSECONDS);
}
}
private long deleteUnusedFilesBetween(final Instant lowerBound, final Instant upperBound, final int batchSize) {
long deleted;
long totalDeleted = 0L;
do {
deleted = this.persistenceService.deleteUnusedFiles(lowerBound, upperBound, batchSize);
totalDeleted += deleted;
} while (deleted > 0);
return totalDeleted;
}
private void deleteTags(final Instant creationThreshold) {
final long startTime = System.nanoTime();
final Set<Tag> tags = Sets.newHashSet();
try {
final boolean skipTags = this.environment.getProperty(
DatabaseCleanupProperties.TagDatabaseCleanupProperties.SKIP_PROPERTY,
Boolean.class,
this.cleanupProperties.getTagCleanup().isSkip()
);
if (skipTags) {
log.info("Skipping tags cleanup");
this.numDeletedTags.set(0);
} else {
final int batchSize = this.environment.getProperty(
DatabaseCleanupProperties.BATCH_SIZE_PROPERTY,
Integer.class,
this.cleanupProperties.getBatchSize()
);
log.info(
"Attempting to delete unused tags from before {} in batches of {}",
creationThreshold,
batchSize
);
long deleted;
long totalDeleted = 0L;
do {
deleted = this.persistenceService.deleteUnusedTags(creationThreshold, batchSize);
totalDeleted += deleted;
} while (deleted > 0);
log.info(
"Deleted {} tags that were unused by any resource and created before {}",
totalDeleted,
creationThreshold
);
this.numDeletedTags.set(totalDeleted);
}
} catch (final Exception e) {
log.error("Unable to delete tags from database", e);
MetricsUtils.addFailureTagsWithException(tags, e);
} finally {
this.registry
.timer(TAG_DELETION_TIMER, tags)
.record(System.nanoTime() - startTime, TimeUnit.NANOSECONDS);
}
}
private void deactivateCommands(final Instant runtime) {
final long startTime = System.nanoTime();
final Set<Tag> tags = Sets.newHashSet();
try {
final boolean skipDeactivation = this.environment.getProperty(
DatabaseCleanupProperties.CommandDeactivationDatabaseCleanupProperties.SKIP_PROPERTY,
Boolean.class,
this.cleanupProperties.getCommandDeactivation().isSkip()
);
if (skipDeactivation) {
log.info("Skipping command deactivation");
this.numDeactivatedCommands.set(0);
} else {
final int batchSize = this.environment.getProperty(
DatabaseCleanupProperties.BATCH_SIZE_PROPERTY,
Integer.class,
this.cleanupProperties.getBatchSize()
);
final Instant commandCreationThreshold = runtime.minus(
this.environment.getProperty(
DatabaseCleanupProperties
.CommandDeactivationDatabaseCleanupProperties
.COMMAND_CREATION_THRESHOLD_PROPERTY,
Integer.class,
this.cleanupProperties.getCommandDeactivation().getCommandCreationThreshold()
),
ChronoUnit.DAYS
);
log.info(
"Attempting to set commands to status {} that were previously in one of {} in batches of {}",
CommandStatus.INACTIVE,
TO_DEACTIVATE_COMMAND_STATUSES,
batchSize
);
long totalDeactivatedCommands = 0;
long batchedDeactivated;
do {
batchedDeactivated = this.persistenceService.updateStatusForUnusedCommands(
CommandStatus.INACTIVE,
commandCreationThreshold,
TO_DEACTIVATE_COMMAND_STATUSES,
batchSize
);
totalDeactivatedCommands += batchedDeactivated;
} while (batchedDeactivated > 0);
log.info(
"Set {} commands to status {} that were previously in one of {}",
totalDeactivatedCommands,
CommandStatus.INACTIVE,
TO_DEACTIVATE_COMMAND_STATUSES
);
this.numDeactivatedCommands.set(totalDeactivatedCommands);
}
} catch (final Exception e) {
log.error("Unable to disable commands in database", e);
MetricsUtils.addFailureTagsWithException(tags, e);
} finally {
this.registry
.timer(COMMAND_DEACTIVATION_TIMER, tags)
.record(System.nanoTime() - startTime, TimeUnit.NANOSECONDS);
}
}
private void deleteCommands(final Instant creationThreshold) {
final long startTime = System.nanoTime();
final Set<Tag> tags = Sets.newHashSet();
try {
final boolean skipCommands = this.environment.getProperty(
DatabaseCleanupProperties.CommandDatabaseCleanupProperties.SKIP_PROPERTY,
Boolean.class,
this.cleanupProperties.getCommandCleanup().isSkip()
);
if (skipCommands) {
log.info("Skipping command cleanup");
this.numDeletedCommands.set(0);
} else {
final int batchSize = this.environment.getProperty(
DatabaseCleanupProperties.BATCH_SIZE_PROPERTY,
Integer.class,
this.cleanupProperties.getBatchSize()
);
log.info(
"Attempting to delete unused commands from before {} in batches of {}",
creationThreshold,
batchSize
);
long deleted;
long totalDeleted = 0L;
do {
deleted = this.persistenceService.deleteUnusedCommands(
TO_DELETE_COMMAND_STATUSES,
creationThreshold,
batchSize
);
totalDeleted += deleted;
} while (deleted > 0);
log.info(
"Deleted {} commands that were unused by any resource and created before {}",
totalDeleted,
creationThreshold
);
this.numDeletedCommands.set(totalDeleted);
}
} catch (final Exception e) {
log.error("Unable to delete commands in database", e);
MetricsUtils.addFailureTagsWithException(tags, e);
} finally {
this.registry
.timer(COMMAND_DELETION_TIMER, tags)
.record(System.nanoTime() - startTime, TimeUnit.NANOSECONDS);
}
}
private void deleteApplications(final Instant creationThreshold) {
final long startTime = System.nanoTime();
final Set<Tag> tags = Sets.newHashSet();
try {
final boolean skipApplications = this.environment.getProperty(
DatabaseCleanupProperties.ApplicationDatabaseCleanupProperties.SKIP_PROPERTY,
Boolean.class,
this.cleanupProperties.getApplicationCleanup().isSkip()
);
if (skipApplications) {
log.info("Skipping application cleanup");
this.numDeletedCommands.set(0);
} else {
final int batchSize = this.environment.getProperty(
DatabaseCleanupProperties.BATCH_SIZE_PROPERTY,
Integer.class,
this.cleanupProperties.getBatchSize()
);
log.info(
"Attempting to delete unused applications from before {} in batches of {}",
creationThreshold,
batchSize
);
long deleted;
long totalDeleted = 0L;
do {
deleted = this.persistenceService.deleteUnusedApplications(
creationThreshold,
batchSize
);
totalDeleted += deleted;
} while (deleted > 0);
log.info(
"Deleted {} applications that were unused by any resource and created before {}",
totalDeleted,
creationThreshold
);
this.numDeletedApplications.set(totalDeleted);
}
} catch (final Exception e) {
log.error("Unable to delete applications in database", e);
MetricsUtils.addFailureTagsWithException(tags, e);
} finally {
this.registry
.timer(APPLICATION_DELETION_TIMER, tags)
.record(System.nanoTime() - startTime, TimeUnit.NANOSECONDS);
}
}
}
| 2,497 |
0 |
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/tasks
|
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/tasks/leader/package-info.java
|
/*
*
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Classes involved in leadership election and tasks associated with being a cluster leader.
*
* @author tgianos
* @since 3.0.0
*/
package com.netflix.genie.web.tasks.leader;
| 2,498 |
0 |
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/tasks
|
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/tasks/node/package-info.java
|
/*
*
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Classes that run as tasks on every node in a Genie cluster.
*
* @author tgianos
* @since 3.0.0
*/
package com.netflix.genie.web.tasks.node;
| 2,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.