org.springframework.test.annotation.DirtiesContext Java Examples

The following examples show how to use org.springframework.test.annotation.DirtiesContext. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: filterByTests.java    From spring-boot-rest-api-helpers with MIT License 6 votes vote down vote up
@Test
@DirtiesContext(methodMode = DirtiesContext.MethodMode.BEFORE_METHOD)
public void search_text_on_primitive__fetch_movie_by_not_oontaining_name_infix() {
    Movie matrix = new Movie();
    matrix.setName("The Matrix");
    movieRepository.save(matrix);

    Movie constantine = new Movie();
    constantine.setName("The Matrix: Reloaded");
    movieRepository.save(constantine);

    Movie it = new Movie();
    it.setName("IT");
    movieRepository.save(it);

    Iterable<Movie> movieByName = movieController.filterBy(UrlUtils.encodeURIComponent("{nameNot: %atri%}"), null, null);
    Assert.assertEquals(1, IterableUtil.sizeOf(movieByName));
}
 
Example #2
Source File: SimpleTaskRepositoryJdbcTests.java    From spring-cloud-task with Apache License 2.0 6 votes vote down vote up
@Test
@DirtiesContext
public void startTaskExecutionWithParent() {
	TaskExecution expectedTaskExecution = TaskExecutionCreator
			.createAndStoreEmptyTaskExecution(this.taskRepository);

	expectedTaskExecution.setStartTime(new Date());
	expectedTaskExecution.setTaskName(UUID.randomUUID().toString());
	expectedTaskExecution.setParentExecutionId(12345L);

	TaskExecution actualTaskExecution = this.taskRepository.startTaskExecution(
			expectedTaskExecution.getExecutionId(),
			expectedTaskExecution.getTaskName(), expectedTaskExecution.getStartTime(),
			expectedTaskExecution.getArguments(),
			expectedTaskExecution.getExternalExecutionId(),
			expectedTaskExecution.getParentExecutionId());

	TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, actualTaskExecution);
}
 
Example #3
Source File: BaseTaskExecutionDaoTestCases.java    From spring-cloud-task with Apache License 2.0 6 votes vote down vote up
/**
 * This test is a special use-case. While not common, it is theoretically possible,
 * that a task may have executed with the exact same start time multiple times. In
 * that case we should still only get 1 returned {@link TaskExecution}.
 */
@Test
@DirtiesContext
public void getLatestTaskExecutionsByTaskNamesWithIdenticalTaskExecutions() {
	long executionIdOffset = initializeRepositoryNotInOrderWithMultipleTaskExecutions();
	final List<TaskExecution> latestTaskExecutions = this.dao
			.getLatestTaskExecutionsByTaskNames("FOO5");
	assertThat(latestTaskExecutions.size() == 1).as(
			"Expected only 1 taskExecution but got " + latestTaskExecutions.size())
			.isTrue();

	final Calendar dateTime = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
	dateTime.setTime(latestTaskExecutions.get(0).getStartTime());

	assertThat(dateTime.get(Calendar.YEAR)).isEqualTo(2015);
	assertThat(dateTime.get(Calendar.MONTH) + 1).isEqualTo(2);
	assertThat(dateTime.get(Calendar.DAY_OF_MONTH)).isEqualTo(22);
	assertThat(dateTime.get(Calendar.HOUR_OF_DAY)).isEqualTo(23);
	assertThat(dateTime.get(Calendar.MINUTE)).isEqualTo(59);
	assertThat(dateTime.get(Calendar.SECOND)).isEqualTo(0);
	assertThat(latestTaskExecutions.get(0).getExecutionId())
			.isEqualTo(9 + executionIdOffset);
}
 
Example #4
Source File: RefreshableConfigurationTest.java    From memcached-spring-boot with Apache License 2.0 6 votes vote down vote up
@Test
@DirtiesContext
public void whenConfigurationChangedThenMemcachedClientReinitialized() {
    Object beforeRefresh = ReflectionTestUtils.getField(cacheManager, "memcachedClient");
    assertMemcachedClient((IMemcachedClient) beforeRefresh);

    TestPropertyValues.of(
        "memcached.cache.prefix:test-prefix",
        "memcached.cache.protocol:binary"
    ).applyTo(environment);

    refresher.refresh();

    Object expiration = ReflectionTestUtils.getField(cacheManager, "expiration");
    Object prefix = ReflectionTestUtils.getField(cacheManager, "prefix");
    Object afterRefresh = ReflectionTestUtils.getField(cacheManager, "memcachedClient");

    assertThat(expiration).isNotNull();
    assertThat(expiration).isEqualTo(Default.EXPIRATION);
    assertThat(prefix).isNotNull();
    assertThat(prefix).isEqualTo("test-prefix");
    assertMemcachedClient((IMemcachedClient) afterRefresh,
            MemcachedCacheProperties.Protocol.BINARY, Default.OPERATION_TIMEOUT);
}
 
Example #5
Source File: JdbcTaskExecutionDaoTests.java    From spring-cloud-task with Apache License 2.0 6 votes vote down vote up
@Test
@DirtiesContext
public void testStartTaskExecution() {
	TaskExecution expectedTaskExecution = this.dao.createTaskExecution(null, null,
			new ArrayList<>(0), null);

	expectedTaskExecution.setArguments(
			Collections.singletonList("foo=" + UUID.randomUUID().toString()));
	expectedTaskExecution.setStartTime(new Date());
	expectedTaskExecution.setTaskName(UUID.randomUUID().toString());

	this.dao.startTaskExecution(expectedTaskExecution.getExecutionId(),
			expectedTaskExecution.getTaskName(), expectedTaskExecution.getStartTime(),
			expectedTaskExecution.getArguments(),
			expectedTaskExecution.getExternalExecutionId());

	TestVerifierUtils.verifyTaskExecution(expectedTaskExecution,
			TestDBUtils.getTaskExecutionFromDB(this.dataSource,
					expectedTaskExecution.getExecutionId()));
}
 
Example #6
Source File: DefaultTaskExecutionServiceTests.java    From spring-cloud-dataflow with Apache License 2.0 6 votes vote down vote up
@Test
@DirtiesContext
public void getCFTaskLog() {
	String platformName = "cf-test-platform";
	String taskDefinitionName = "test";
	String taskDeploymentId = "12345";
	TaskDeployment taskDeployment = new TaskDeployment();
	taskDeployment.setPlatformName(platformName);
	taskDeployment.setTaskDefinitionName(taskDefinitionName);
	taskDeployment.setTaskDeploymentId(taskDeploymentId);
	this.taskDeploymentRepository.save(taskDeployment);
	this.launcherRepository.save(new Launcher(platformName,
			TaskPlatformFactory.CLOUDFOUNDRY_PLATFORM_TYPE, taskLauncher));
	when(taskLauncher.getLog(taskDefinitionName)).thenReturn("Logs");
	assertEquals("Logs", this.taskExecutionService.getLog(taskDeployment.getPlatformName(), taskDeploymentId));
}
 
Example #7
Source File: EncryptSystemTest.java    From spring-data-mongodb-encrypt with Apache License 2.0 6 votes vote down vote up
@Test(expected = DocumentCryptException.class)
@DirtiesContext
public void checkWrongKeyCustomId() {
    // save to db, version = 0
    MyBean bean = new MyBean();
    bean.id = "customId";
    bean.secretString = "secret";
    bean.nonSensitiveData = getClass().getSimpleName();
    mongoTemplate.insert(bean);

    // override version 0's key
    ReflectionTestUtils.setField(cryptVault, "cryptVersions", new CryptVersion[256]);
    cryptVault.with256BitAesCbcPkcs5PaddingAnd128BitSaltKey(0, Base64.getDecoder().decode("aic7QGYCCSHyy7gYRCyNTpPThbomw1/dtWl4bocyTnU="));

    try {
        mongoTemplate.find(query(where(MONGO_NONSENSITIVEDATA).is(getClass().getSimpleName())), MyBean.class);
    } catch (DocumentCryptException e) {
        assertCryptException(e, "mybean", null, "secretString");
        throw e;
    }
}
 
Example #8
Source File: PartitionTemplateWithEmfTest.java    From score with Apache License 2.0 6 votes vote down vote up
@Test
@DirtiesContext
public void updatePartitionGroup() {
    service.createPartitionGroup(tableName, Integer.MAX_VALUE, Long.MAX_VALUE, Long.MAX_VALUE);

    final String newGroupName = "newName";
    final int newGroupSize = 10;
    final int newTimeThreshold = 20;
    final int newSizeThreshold = 30;

    service.updatePartitionGroup(newGroupName, newGroupSize, newTimeThreshold, newSizeThreshold);

    applicationContext.getBean(tableName, PartitionTemplate.class);
    PartitionGroup partitionGroup = service.readPartitionGroup(tableName);
    assertThat(partitionGroup.getName().equals(newGroupName));
    assertThat(partitionGroup.getGroupSize() == newGroupSize);
    assertThat(partitionGroup.getSizeThreshold() == newTimeThreshold);
    assertThat(partitionGroup.getSizeThreshold() == newSizeThreshold);
}
 
Example #9
Source File: ITExchangeGatewayHttp.java    From exchange-gateway-rest with Apache License 2.0 6 votes vote down vote up
@Test
@DirtiesContext
public void shouldAddNewSymbol() throws Exception {

    gatewayTestClient.addAsset(new RestApiAdminAsset("XBTC", 9123, 8));
    gatewayTestClient.addAsset(new RestApiAdminAsset("USDT", 3412, 2));

    gatewayTestClient.addSymbol(new RestApiAddSymbol(
            "XBTC_USDT",
            3199,
            SymbolType.CURRENCY_EXCHANGE_PAIR,
            "XBTC",
            "USDT",
            new BigDecimal("1000"),
            new BigDecimal("1"),
            new BigDecimal("0.08"),
            new BigDecimal("0.03"),
            BigDecimal.ZERO,
            BigDecimal.ZERO,
            new BigDecimal("50000"),
            new BigDecimal("1000")));
}
 
Example #10
Source File: filterByTests.java    From spring-boot-rest-api-helpers with MIT License 6 votes vote down vote up
@Test
@DirtiesContext(methodMode = DirtiesContext.MethodMode.BEFORE_METHOD)
public void fetch_by_multiple_ids__fetch_movies_by_ids() {
    Movie matrix = new Movie();
    matrix.setName("The Matrix");
    movieRepository.save(matrix);

    Movie constantine = new Movie();
    constantine.setName("Constantine");
    movieRepository.save(constantine);

    Movie it = new Movie();
    it.setName("IT");
    movieRepository.save(it);

    Iterable<Movie> moviesById = movieController.filterBy("{ id: ["+matrix.getId()+","+constantine.getId()+"]}", null, null);
    Assert.assertEquals(2, IterableUtil.sizeOf(moviesById));
}
 
Example #11
Source File: CreateElementsIT.java    From difido-reports with Apache License 2.0 6 votes vote down vote up
@Test
@DirtiesContext(classMode = ClassMode.BEFORE_EACH_TEST_METHOD)
public void testAddReportElement() throws Exception {
	ReportElement element = new ReportElement(details);
	element.setType(ElementType.regular);
	element.setTime("00:00");
	final String title = "My report element";
	element.setTitle(title);
	final String message = "My report element message";
	element.setMessage(message);
	details.addReportElement(element);
	client.addTestDetails(executionId, details);

	waitForTasksToFinish();
	final TestDetails testDetails = assertExecution();
	element = testDetails.getReportElements().get(0);
	Assert.assertEquals(ElementType.regular, element.getType());
	Assert.assertEquals(title, element.getTitle());
	Assert.assertEquals(message, element.getMessage());

}
 
Example #12
Source File: TaskJobLauncherCommandLineRunnerCoreTests.java    From spring-cloud-task with Apache License 2.0 6 votes vote down vote up
@DirtiesContext
@Test
public void retryFailedExecutionOnNonRestartableJob() throws Exception {
	this.job = this.jobs.get("job").preventRestart()
			.start(this.steps.get("step").tasklet(throwingTasklet()).build())
			.incrementer(new RunIdIncrementer()).build();
	runFailedJob(new JobParameters());
	runFailedJob(new JobParameters());
	// A failed job that is not restartable does not re-use the job params of
	// the last execution, but creates a new job instance when running it again.
	assertThat(this.jobExplorer.getJobInstances("job", 0, 100)).hasSize(2);

	// try to re-run a failed execution
	Executable executable = () -> this.runner.execute(this.job,
			new JobParametersBuilder().addLong("run.id", 1L).toJobParameters());
	assertThatExceptionOfType(JobRestartException.class)
			.isThrownBy(executable::execute)
			.withMessage("JobInstance already exists and is not restartable");
}
 
Example #13
Source File: DefaultTaskExecutionServiceTests.java    From spring-cloud-dataflow with Apache License 2.0 6 votes vote down vote up
@Test
@DirtiesContext
public void verifyComposedTaskFlag() {
	String composedTaskDsl = "<AAA || BBB>";
	assertTrue("Expected true for composed task", TaskServiceUtils.isComposedTaskDefinition(composedTaskDsl));
	composedTaskDsl = "AAA 'FAILED' -> BBB '*' -> CCC";
	assertTrue("Expected true for composed task", TaskServiceUtils.isComposedTaskDefinition(composedTaskDsl));
	composedTaskDsl = "AAA && BBB && CCC";
	assertTrue("Expected true for composed task", TaskServiceUtils.isComposedTaskDefinition(composedTaskDsl));
	String nonComposedTaskDsl = "AAA";
	assertFalse("Expected false for non-composed task",
			TaskServiceUtils.isComposedTaskDefinition(nonComposedTaskDsl));
	nonComposedTaskDsl = "AAA --foo=bar";
	assertFalse("Expected false for non-composed task",
			TaskServiceUtils.isComposedTaskDefinition(nonComposedTaskDsl));
}
 
Example #14
Source File: SimpleTaskRepositoryJdbcTests.java    From spring-cloud-task with Apache License 2.0 6 votes vote down vote up
@Test
@DirtiesContext
public void startTaskExecutionWithNoParam() {
	TaskExecution expectedTaskExecution = TaskExecutionCreator
			.createAndStoreEmptyTaskExecution(this.taskRepository);

	expectedTaskExecution.setStartTime(new Date());
	expectedTaskExecution.setTaskName(UUID.randomUUID().toString());

	TaskExecution actualTaskExecution = this.taskRepository.startTaskExecution(
			expectedTaskExecution.getExecutionId(),
			expectedTaskExecution.getTaskName(), expectedTaskExecution.getStartTime(),
			expectedTaskExecution.getArguments(),
			expectedTaskExecution.getExternalExecutionId());

	TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, actualTaskExecution);
}
 
Example #15
Source File: JdbcMapWithoutSchedulingTests.java    From CogStack-Pipeline with Apache License 2.0 6 votes vote down vote up
@Test
@DirtiesContext
public void jdbcMapPipelineTest() {
    jobLauncher.launchJob();

    try {
        testUtils.waitForEsReady(30000);
    } catch (RuntimeException e) {
        e.printStackTrace();
    }
    Map<String, Object> row = dbmsTestUtils.getRowInOutputTable(1);
    String stringContent = (String) row.getOrDefault("output", "");
    assertTrue(stringContent.contains("Disproportionate dwarfism"));
    assertEquals(65, dbmsTestUtils.countRowsInOutputTable());
    assertEquals(65, testUtils.countOutputDocsInES());
}
 
Example #16
Source File: RefreshScopeIntegrationTests.java    From spring-cloud-commons with Apache License 2.0 6 votes vote down vote up
@Test
@DirtiesContext
public void testRefresh() throws Exception {
	then(this.service.getMessage()).isEqualTo("Hello scope!");
	String id1 = this.service.toString();
	// Change the dynamic property source...
	this.properties.setMessage("Foo");
	// ...and then refresh, so the bean is re-initialized:
	this.scope.refreshAll();
	String id2 = this.service.toString();
	then(this.service.getMessage()).isEqualTo("Foo");
	then(ExampleService.getInitCount()).isEqualTo(1);
	then(ExampleService.getDestroyCount()).isEqualTo(1);
	then(id2).isNotSameAs(id1);
	then(ExampleService.event).isNotNull();
	then(ExampleService.event.getName())
			.isEqualTo(RefreshScopeRefreshedEvent.DEFAULT_NAME);
}
 
Example #17
Source File: CreateElementsIT.java    From difido-reports with Apache License 2.0 6 votes vote down vote up
@Test
@DirtiesContext(classMode = ClassMode.BEFORE_EACH_TEST_METHOD)
public void measureAddReportElements() throws Exception {
	ReportElement element = null;
	for (int i = 0; i < NUM_OF_REPORTS_ELEMENTS; i++) {
		element = new ReportElement(details);
		element.setType(ElementType.regular);
		element.setTime("00:" + i);
		element.setTitle("My report element " + i);
		details.addReportElement(element);
		long start = System.currentTimeMillis();
		client.addTestDetails(executionId, details);
		System.out.println("Element was added in " + (System.currentTimeMillis() - start) + " millis");
	}
	waitForTasksToFinish();
	assertExecution();
	System.out.println("End");

}
 
Example #18
Source File: RefreshScopePureScaleTests.java    From spring-cloud-commons with Apache License 2.0 5 votes vote down vote up
@Test
@Repeat(10)
@DirtiesContext
public void testConcurrentRefresh() throws Exception {

	// overload the thread pool and try to force Spring to create too many instances
	int n = 80;
	this.scope.refreshAll();
	final CountDownLatch latch = new CountDownLatch(n);
	List<Future<String>> results = new ArrayList<>();
	for (int i = 0; i < n; i++) {
		results.add(this.executor.submit(new Callable<String>() {
			@Override
			public String call() throws Exception {
				logger.debug("Background started.");
				try {
					return RefreshScopePureScaleTests.this.service.getMessage();
				}
				finally {
					latch.countDown();
					logger.debug("Background done.");
				}
			}
		}));
		this.executor.submit(new Runnable() {
			@Override
			public void run() {
				logger.debug("Refreshing.");
				RefreshScopePureScaleTests.this.scope.refreshAll();
			}
		});
	}
	then(latch.await(15000, TimeUnit.MILLISECONDS)).isTrue();
	then(this.service.getMessage()).isEqualTo("Foo");
	for (Future<String> result : results) {
		then(result.get()).isEqualTo("Foo");
	}
}
 
Example #19
Source File: AbstractDirtiesContextTestExecutionListener.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Perform the actual work for {@link #beforeTestMethod} and {@link #afterTestMethod}
 * by dirtying the context if appropriate (i.e., according to the required modes).
 * @param testContext the test context whose application context should
 * potentially be marked as dirty; never {@code null}
 * @param requiredMethodMode the method mode required for a context to
 * be marked dirty in the current phase; never {@code null}
 * @param requiredClassMode the class mode required for a context to
 * be marked dirty in the current phase; never {@code null}
 * @throws Exception allows any exception to propagate
 * @since 4.2
 * @see #dirtyContext
 */
protected void beforeOrAfterTestMethod(TestContext testContext, MethodMode requiredMethodMode,
		ClassMode requiredClassMode) throws Exception {

	Assert.notNull(testContext, "TestContext must not be null");
	Assert.notNull(requiredMethodMode, "requiredMethodMode must not be null");
	Assert.notNull(requiredClassMode, "requiredClassMode must not be null");

	Class<?> testClass = testContext.getTestClass();
	Method testMethod = testContext.getTestMethod();
	Assert.notNull(testClass, "The test class of the supplied TestContext must not be null");
	Assert.notNull(testMethod, "The test method of the supplied TestContext must not be null");

	DirtiesContext methodAnn = AnnotatedElementUtils.findMergedAnnotation(testMethod, DirtiesContext.class);
	DirtiesContext classAnn = AnnotatedElementUtils.findMergedAnnotation(testClass, DirtiesContext.class);
	boolean methodAnnotated = (methodAnn != null);
	boolean classAnnotated = (classAnn != null);
	MethodMode methodMode = (methodAnnotated ? methodAnn.methodMode() : null);
	ClassMode classMode = (classAnnotated ? classAnn.classMode() : null);

	if (logger.isDebugEnabled()) {
		String phase = (requiredClassMode.name().startsWith("BEFORE") ? "Before" : "After");
		logger.debug(String.format("%s test method: context %s, class annotated with @DirtiesContext [%s] "
				+ "with mode [%s], method annotated with @DirtiesContext [%s] with mode [%s].", phase, testContext,
			classAnnotated, classMode, methodAnnotated, methodMode));
	}

	if ((methodMode == requiredMethodMode) || (classMode == requiredClassMode)) {
		HierarchyMode hierarchyMode = (methodAnnotated ? methodAnn.hierarchyMode() : classAnn.hierarchyMode());
		dirtyContext(testContext, hierarchyMode);
	}
}
 
Example #20
Source File: SingleShardMigrationTest.java    From x-pipe with Apache License 2.0 5 votes vote down vote up
@Test
@DirtiesContext
public void testSuccess() {
	mockSuccessCheckCommand(migrationCommandBuilder,"cluster1", "shard1", dcB, dcB);
	mockSuccessPrevPrimaryDcCommand(migrationCommandBuilder,"cluster1", "shard1", dcA);
	mockSuccessNewPrimaryDcCommand(migrationCommandBuilder,"cluster1", "shard1", dcB);
	mockSuccessOtherDcCommand(migrationCommandBuilder,"cluster1", "shard1", dcB, dcA);

	
	ClusterTbl originalCluster = clusterService.find(1);
	Assert.assertEquals(ClusterStatus.Lock.toString(), originalCluster.getStatus());
	Assert.assertEquals(1, originalCluster.getActivedcId());
	Assert.assertEquals(1, migrationCluster.getMigrationCluster().getSourceDcId());
	Assert.assertEquals(2, migrationCluster.getMigrationCluster().getDestinationDcId());
	Assert.assertEquals("Initiated", migrationCluster.getStatus().toString());
	Assert.assertEquals(ShardMigrationResultStatus.FAIL, migrationShard.getShardMigrationResult().getStatus());
	Assert.assertFalse(migrationShard.getShardMigrationResult().stepSuccess(ShardMigrationStep.CHECK));
	Assert.assertFalse(migrationShard.getShardMigrationResult().stepSuccess(ShardMigrationStep.MIGRATE_PREVIOUS_PRIMARY_DC));
	Assert.assertFalse(migrationShard.getShardMigrationResult().stepSuccess(ShardMigrationStep.MIGRATE_NEW_PRIMARY_DC));
	Assert.assertFalse(migrationShard.getShardMigrationResult().stepSuccess(ShardMigrationStep.MIGRATE_OTHER_DC));
	Assert.assertFalse(migrationShard.getShardMigrationResult().stepSuccess(ShardMigrationStep.MIGRATE));
	
	migrationCluster.process();
	sleep(1000);
	
	ClusterTbl currentCluster = clusterService.find(1);
	Assert.assertEquals(ClusterStatus.Normal.toString(), currentCluster.getStatus());
	Assert.assertEquals(2, currentCluster.getActivedcId());
	Assert.assertEquals(ShardMigrationResultStatus.SUCCESS, migrationShard.getShardMigrationResult().getStatus());
	Assert.assertTrue(migrationShard.getShardMigrationResult().stepSuccess(ShardMigrationStep.CHECK));
	Assert.assertTrue(migrationShard.getShardMigrationResult().stepSuccess(ShardMigrationStep.MIGRATE_PREVIOUS_PRIMARY_DC));
	Assert.assertTrue(migrationShard.getShardMigrationResult().stepSuccess(ShardMigrationStep.MIGRATE_NEW_PRIMARY_DC));
	Assert.assertTrue(migrationShard.getShardMigrationResult().stepSuccess(ShardMigrationStep.MIGRATE_OTHER_DC));
	Assert.assertTrue(migrationShard.getShardMigrationResult().stepSuccess(ShardMigrationStep.MIGRATE));
	
	ClusterMeta prevPrimaryDcMeta = clusterMetaService.getClusterMeta(dcA, "cluster1");
	Assert.assertEquals(dcB, prevPrimaryDcMeta.getActiveDc());
	ClusterMeta newPrimaryDcMeta = clusterMetaService.getClusterMeta(dcB, "cluster1");
	Assert.assertEquals(dcB, newPrimaryDcMeta.getActiveDc());
}
 
Example #21
Source File: ContextRefresherIntegrationTests.java    From spring-cloud-commons with Apache License 2.0 5 votes vote down vote up
@Test
@DirtiesContext
public void testSimpleProperties() throws Exception {
	then(this.properties.getMessage()).isEqualTo("Hello scope!");
	// Change the dynamic property source...
	this.properties.setMessage("Foo");
	// ...but don't refresh, so the bean stays the same:
	then(this.properties.getMessage()).isEqualTo("Foo");
}
 
Example #22
Source File: SpringRunnerContextCacheTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
@DirtiesContext
public void dirtyContext() {
	assertContextCacheStatistics("dirtyContext()", 1, 0, 1);
	assertNotNull("The application context should have been autowired.", this.applicationContext);
	SpringRunnerContextCacheTests.dirtiedApplicationContext = this.applicationContext;
}
 
Example #23
Source File: AbstractSecurityTest.java    From grpc-spring-boot-starter with MIT License 5 votes vote down vote up
/**
 * Tests with server streaming call.
 *
 * @return The tests.
 */
@Test
@DirtiesContext
public DynamicTestCollection serverStreamingCallTests() {
    return DynamicTestCollection.create()
            .add("serverStreaming-default",
                    () -> assertServerStreamingCallSuccess(this.serviceStub))
            .add("serverStreaming-noPerm",
                    () -> assertServerStreamingCallFailure(this.noPermStub, PERMISSION_DENIED));
}
 
Example #24
Source File: AdderMethodDirtiesContextInitWorkaroundIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@DirtiesContext
@Test
public void _0_givenNumber_whenAddAndAccumulate_thenSummedUp() {
    adderServiceSteps.whenAccumulate();
    adderServiceSteps.summedUp();

    adderServiceSteps.whenAdd();
    adderServiceSteps.sumWrong();
}
 
Example #25
Source File: AbstractSecurityWithBasicAuthTest.java    From grpc-spring-boot-starter with MIT License 5 votes vote down vote up
@Override
@Test
@DirtiesContext
@TestFactory
public DynamicTestCollection bidiStreamingCallTests() {
    return super.bidiStreamingCallTests()
            .add("bidiStreaming-unknownUser",
                    () -> assertServerStreamingCallFailure(this.unknownUserStub, UNAUTHENTICATED))
            .add("bidiStreaming-noAuth",
                    () -> assertServerStreamingCallFailure(this.noAuthStub, UNAUTHENTICATED));
}
 
Example #26
Source File: filterByTests.java    From spring-boot-rest-api-helpers with MIT License 5 votes vote down vote up
@Test
@DirtiesContext(methodMode = DirtiesContext.MethodMode.BEFORE_METHOD)
public void reference_many_to_one_null__fetch_movies_with_no_director() {
    Director lana = new Director();
    lana.setFirstName("Lana");
    lana.setLastName("Wachowski");
    directorRepository.save(lana);


    Movie matrix = new Movie();
    matrix.setName("The Matrix");
    matrix.setDirector(lana);
    movieRepository.save(matrix);


    Movie constantine = new Movie();
    constantine.setName("Constantine");
    movieRepository.save(constantine);

    Movie it = new Movie();
    it.setName("IT");
    movieRepository.save(it);


    Iterable<Movie> noDirectorMovies = movieController.filterBy("{director: null}", null, null);
    Assert.assertEquals(2, IterableUtil.sizeOf(noDirectorMovies));
}
 
Example #27
Source File: SnifferJobTest.java    From logsniffer with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
@DirtiesContext
public void testStoppingJobWhenResourcesNotFound() throws Exception {
	final Sniffer sniffer = new Sniffer();
	sniffer.setId(23);
	sniffer.setScheduleCronExpression("*/15 * * ? * * */50");
	sniffer.setLogSourceId(77);
	when(snifferPersistence.getSniffer(23)).thenReturn(sniffer);
	final ScheduleInfo info = new ScheduleInfo();
	when(scheduleInfoAccess.getScheduleInfo(23)).thenReturn(info);
	jobManager.startSniffing(sniffer.getId());
	Assert.assertEquals(true, info.isScheduled());
	Assert.assertNull(info.getLastFireTime());
	verify(scheduleInfoAccess).updateScheduleInfo(23, info);
	Assert.assertEquals(true, jobManager.isScheduled(sniffer.getId()));
	when(snifferPersistence.getSniffer(23)).thenReturn(null);
	scheduler.triggerJob(jobManager.getJobKey(sniffer, 77));
	Thread.sleep(2000);

	// Should be stopped
	verify(snifferPersistence, times(2)).getSniffer(23);
	verifyZeroInteractions(sourceProvider);
	Assert.assertFalse(scheduler.checkExists(jobManager.getJobKey(sniffer, 77)));

	Assert.assertEquals(false, info.isScheduled());
	Assert.assertNotNull(info.getLastFireTime());
	verify(scheduleInfoAccess, times(3)).updateScheduleInfo(23, info);

	// Pass sniffer, but no log source
	when(snifferPersistence.getSniffer(23)).thenReturn(sniffer);
	jobManager.startSniffing(sniffer.getId());
	scheduler.triggerJob(jobManager.getJobKey(sniffer, 77));
	Thread.sleep(2000);
	verify(snifferPersistence, times(4)).getSniffer(23);
	verify(sourceProvider, times(1)).getSourceById(77);
}
 
Example #28
Source File: DefaultTaskExecutionServiceTests.java    From spring-cloud-dataflow with Apache License 2.0 5 votes vote down vote up
@Test
@DirtiesContext
public void deleteComposedTask() {
	initializeSuccessfulRegistry(appRegistry);
	String dsl = "AAA && BBB && CCC";
	taskSaveService.saveTaskDefinition(new TaskDefinition("deleteTask", dsl));
	verifyTaskExistsInRepo("deleteTask-AAA", "AAA", taskDefinitionRepository);
	verifyTaskExistsInRepo("deleteTask-BBB", "BBB", taskDefinitionRepository);
	verifyTaskExistsInRepo("deleteTask-CCC", "CCC", taskDefinitionRepository);
	verifyTaskExistsInRepo("deleteTask", dsl, taskDefinitionRepository);

	long preDeleteSize = taskDefinitionRepository.count();
	taskDeleteService.deleteTaskDefinition("deleteTask");
	assertThat(preDeleteSize - 4, is(equalTo(taskDefinitionRepository.count())));
}
 
Example #29
Source File: ConfigurationPropertiesRebinderIntegrationTests.java    From spring-cloud-commons with Apache License 2.0 5 votes vote down vote up
@Test
@DirtiesContext
public void testSimpleProperties() throws Exception {
	then(this.properties.getMessage()).isEqualTo("Hello scope!");
	then(this.properties.getCount()).isEqualTo(1);
	// Change the dynamic property source...
	TestPropertyValues.of("message:Foo").applyTo(this.environment);
	// ...but don't refresh, so the bean stays the same:
	then(this.properties.getMessage()).isEqualTo("Hello scope!");
	then(this.properties.getCount()).isEqualTo(1);
}
 
Example #30
Source File: ClusterMetaServiceTest.java    From x-pipe with Apache License 2.0 5 votes vote down vote up
@Test
@DirtiesContext
public void testFindMigratingClusterMeta() {
	ClusterTbl cluster = clusterService.find(clusterName2);
	Assert.assertEquals(ClusterStatus.Migrating.toString(), cluster.getStatus());
	
	ClusterMeta clusterMetaA = clusterMetaService.getClusterMeta(dcA, clusterName2);
	ClusterMeta clusterMetaB = clusterMetaService.getClusterMeta(dcB, clusterName2);
	Assert.assertEquals(dcA, clusterMetaA.getActiveDc());
	Assert.assertEquals(dcB, clusterMetaB.getActiveDc());
}