@Test public void testTakeZeroDoesntLeakError() { final AtomicBoolean subscribed = new AtomicBoolean(false); final AtomicBoolean unSubscribed = new AtomicBoolean(false); Observable<String> source = Observable.create( new Func1<Observer<String>, Subscription>() { @Override public Subscription call(Observer<String> observer) { subscribed.set(true); observer.onError(new Throwable("test failed")); return new Subscription() { @Override public void unsubscribe() { unSubscribed.set(true); } }; } }); @SuppressWarnings("unchecked") Observer<String> aObserver = mock(Observer.class); Observable.create(take(source, 0)).subscribe(aObserver); assertTrue("source subscribed", subscribed.get()); assertTrue("source unsubscribed", unSubscribed.get()); verify(aObserver, never()).onNext(anyString()); // even though onError is called we take(0) so shouldn't see it verify(aObserver, never()).onError(any(Throwable.class)); verify(aObserver, times(1)).onCompleted(); verifyNoMoreInteractions(aObserver); }
@Test public void testUnSubscribe() { TestObservable tA = new TestObservable(); TestObservable tB = new TestObservable(); @SuppressWarnings("unchecked") Observable<String> m = Observable.create(merge(tA, tB)); Subscription s = m.subscribe(stringObserver); tA.sendOnNext("Aone"); tB.sendOnNext("Bone"); s.unsubscribe(); tA.sendOnNext("Atwo"); tB.sendOnNext("Btwo"); tA.sendOnCompleted(); tB.sendOnCompleted(); verify(stringObserver, never()).onError(any(Exception.class)); verify(stringObserver, times(1)).onNext("Aone"); verify(stringObserver, times(1)).onNext("Bone"); assertTrue(tA.unsubscribed); assertTrue(tB.unsubscribed); verify(stringObserver, never()).onNext("Atwo"); verify(stringObserver, never()).onNext("Btwo"); verify(stringObserver, never()).onCompleted(); }
@Test public void testGetComplianceStatusList() { Consumer c = mock(Consumer.class); Consumer c2 = mock(Consumer.class); when(c.getUuid()).thenReturn("1"); when(c2.getUuid()).thenReturn("2"); List<Consumer> consumers = new ArrayList<Consumer>(); consumers.add(c); consumers.add(c2); List<String> uuids = new ArrayList<String>(); uuids.add("1"); uuids.add("2"); when(mockedConsumerCurator.findByUuids(eq(uuids))).thenReturn(consumers); ComplianceStatus status = new ComplianceStatus(); when(mockedComplianceRules.getStatus(any(Consumer.class), any(Date.class))).thenReturn(status); ConsumerResource cr = new ConsumerResource( mockedConsumerCurator, null, null, null, null, null, null, i18n, null, null, null, null, null, null, null, null, null, null, mockedComplianceRules, null, null, null, new CandlepinCommonTestConfig(), null, null, null, consumerBindUtil, productCurator, null); Map<String, ComplianceStatus> results = cr.getComplianceStatusList(uuids); assertEquals(2, results.size()); assertTrue(results.containsKey("1")); assertTrue(results.containsKey("2")); }
@Test public void testAddWorkspace() { int startingVertexCount = graph.getAllVertices().size(); int startingEdgeCount = graph.getAllEdges().size(); String workspaceId = "testWorkspaceId"; idGenerator.push(workspaceId); idGenerator.push(workspaceId + "_to_" + user1.getUserId()); Workspace workspace = workspaceRepository.add("workspace1", user1); assertTrue( authorizationRepository .getGraphAuthorizations() .contains(WorkspaceRepository.WORKSPACE_ID_PREFIX + workspaceId)); assertEquals( startingVertexCount + 1, graph.getAllVertices().size()); // +1 = the workspace vertex assertEquals( startingEdgeCount + 1, graph.getAllEdges().size()); // +1 = the edge between workspace and user1 assertNull( "Should not have access", graph.getVertex(workspace.getId(), new InMemoryAuthorizations())); InMemoryAuthorizations authorizations = new InMemoryAuthorizations(WorkspaceRepository.VISIBILITY_STRING, workspace.getId()); assertNotNull("Should have access", graph.getVertex(workspace.getId(), authorizations)); Workspace foundWorkspace = workspaceRepository.findById(workspace.getId(), user1); assertEquals(workspace.getId(), foundWorkspace.getId()); }
@Test public void testPublishLast() throws InterruptedException { final AtomicInteger count = new AtomicInteger(); ConnectableObservable<String> connectable = Observable.<String>create( observer -> { observer.onSubscribe(EmptySubscription.INSTANCE); count.incrementAndGet(); new Thread( () -> { observer.onNext("first"); observer.onNext("last"); observer.onComplete(); }) .start(); }) .takeLast(1) .publish(); // subscribe once final CountDownLatch latch = new CountDownLatch(1); connectable.subscribe( value -> { assertEquals("last", value); latch.countDown(); }); // subscribe twice connectable.subscribe(); Disposable subscription = connectable.connect(); assertTrue(latch.await(1000, TimeUnit.MILLISECONDS)); assertEquals(1, count.get()); subscription.dispose(); }
@Test public void testGetRankedCertifications() { List<CertificationType> certifications = new ArrayList<CertificationType>(); Certification cert1 = CredentialFactory.getInstance().createCertification(); Certification cert2 = CredentialFactory.getInstance().createCertification(); Certification cert3 = CredentialFactory.getInstance().createCertification(); certifications.add(cert1.getCertificationType()); certifications.add(cert2.getCertificationType()); certifications.add(cert3.getCertificationType()); when(mockDataService.getAllRanked(CertificationType.class)).thenReturn(certifications); List<CertificationType> rankedCertifications = action.getRankedCertifications(); assertNotNull(rankedCertifications); assertEquals(3, rankedCertifications.size()); assertTrue(rankedCertifications.contains(cert1.getCertificationType())); assertTrue(rankedCertifications.contains(cert2.getCertificationType())); assertTrue(rankedCertifications.contains(cert3.getCertificationType())); }
@Test public void shouldDetectNonDerivedResources() throws CoreException { when(resource.getType()).thenReturn(IResource.FILE); when(resource.isDerived()).thenReturn(false); assertFalse(deltaVisitor.visit(resourceDelta(CONTENT))); assertTrue(deltaVisitor.savedResourceFound()); }
@Test public void renderStartPageWithXMLModel() { Szenario szenario = szenario("s1"); SzenarioUserData szenarioUserData = new SzenarioUserData(); szenarioUserData.setProjektname("projekt abc"); AnwenderloesungRenderingContainer container = new AnwenderloesungRenderingContainer( "id", szenario, szenarioUserData, Arrays.asList("de"), true, true, true, true); String x = renderer.renderStartPage( container, new LocalizationEngine(localizationEngineSupport, "model", "de")); assertTrue(x, x.contains("projekt abc")); assertTrue(x, x.toLowerCase().contains("xml")); assertFalse(x, x.contains(szenario.getId())); htmlChecker.checkHtmlString(x); }
@Test public void shouldKeepLookingIfResourceIsNotAFile() throws CoreException { when(resource.isDerived()).thenReturn(false); when(resource.getType()).thenReturn(IResource.FOLDER); assertTrue(deltaVisitor.visit(resourceDelta(CONTENT))); assertFalse(deltaVisitor.savedResourceFound()); }
@Test public void testGenerateTasks_NotASponsor() throws Exception { FirebirdUser coordinator = FirebirdUserFactory.getInstance().createRegistrationCoordinator(); List<Task> tasks = generator.generateTasks(coordinator, null); assertTrue(tasks.isEmpty()); }
@Test public void constructorWithoutPathUsesTmcSettings() throws TmcCoreException { String path = "pentti/tmc/java"; settings.setCurrentCourse(new Course()); settings.setTmcMainDirectory(path); DownloadExercises de = new DownloadExercises(new ArrayList<Exercise>(), settings); assertTrue(de.data.containsKey("path")); assertEquals(path, de.data.get("path")); }
@Test public void assertNewWorkspaceExistsIsNotRetrievingServerList() throws Exception { when(server.execute(isA(MaskedArgumentListBuilder.class))).thenReturn(new StringReader("")); Workspaces workspaces = new Workspaces(server); Workspace workspace = workspaces.newWorkspace("name1"); assertTrue("The get new workspace did not exists", workspaces.exists(workspace)); verify(server, times(1)).execute(isA(MaskedArgumentListBuilder.class)); }
@Test public void assertNewWorkspaceIsAddedToMap() throws Exception { when(server.execute(isA(MaskedArgumentListBuilder.class))).thenReturn(new StringReader("")); Workspaces workspaces = new Workspaces(server); Workspace workspace = workspaces.newWorkspace("name1"); assertNotNull("The new workspace was null", workspace); assertTrue("The workspace was reported as non existant", workspaces.exists(workspace)); }
@Test public void testMigrate_Job() { Job<?, ?> item = mock(Job.class); assertTrue(migrator.migrate(item)); verify(projectMigrator, never()).migrate(any(AbstractProject.class)); verify(jobMigrator).migrate(any(Job.class)); verify(templateMigrator, never()).migrate(any(AbstractProject.class)); }
@Test public void testGenerateTasks_AcceptedSubinvestigatorRegistration() throws Exception { SubInvestigatorRegistration subinvestigatorRegistration = RegistrationFactory.getInstance().createSubinvestigatorRegistration(); subinvestigatorRegistration.setStatus(ACCEPTED); setUpMockRegistrationServiceToReturnRegistration(subinvestigatorRegistration); List<Task> tasks = generator.generateTasks(sponsor, groupNames); assertTrue(tasks.isEmpty()); }
@Test public void when_endpoint_scope_same_as_token_scope_retunr_true() throws Exception { // GIVEN String tokenResponse = "{\"scope\":\"basic\",\"token_type\":\"Bearer\",\"userId\":\"12345\"}"; // WHEN boolean result = AccessTokenValidator.validateTokenScope(tokenResponse, "basic"); // THEN assertTrue(result); }
@Test public void overwritesToCacheFileIfCacheFileHasBadContents() throws IOException, TmcCoreException { new FileWriter(cache).write(" asdfjljlkasdf "); ExerciseDownloader downloader = Mockito.mock(ExerciseDownloader.class); Mockito.when(downloader.createCourseFolder(anyString(), anyString())).thenReturn(""); Mockito.when(downloader.handleSingleExercise(any(Exercise.class), anyString())) .thenReturn(true); Course course = new Course(); course.setName("test-course"); course.setExercises( new ExerciseBuilder() .withExercise("kissa", 2, "eujwuc") .withExercise("asdf", 793, "alnwnec") .withExercise("ankka", 88, "abcdefg") .build()); parser = Mockito.mock(TmcJsonParser.class); Mockito.when(parser.getCourse(anyInt())).thenReturn(Optional.of(course)); DownloadExercises dl = new DownloadExercises(downloader, "", "8", cache, settings, parser); dl.call(); String json = FileUtils.readFileToString(cache); Gson gson = new Gson(); Map<String, Map<String, String>> checksums; Type typeOfHashMap = new TypeToken<Map<String, Map<String, String>>>() {}.getType(); checksums = gson.fromJson(json, typeOfHashMap); assertNotNull(checksums); assertTrue(checksums.containsKey("test-course")); assertTrue(checksums.get("test-course").containsKey("kissa")); assertTrue(checksums.get("test-course").containsKey("asdf")); assertTrue(checksums.get("test-course").containsKey("ankka")); assertEquals("eujwuc", checksums.get("test-course").get("kissa")); assertEquals("alnwnec", checksums.get("test-course").get("asdf")); assertEquals("abcdefg", checksums.get("test-course").get("ankka")); }
@Test public void renderStartPage() { Szenario szenario = szenario("s1"); AnwenderloesungRenderingContainer container = new AnwenderloesungRenderingContainer( "id", szenario, new SzenarioUserData(), Arrays.asList("de"), true, true, true, true); String x = renderer.renderStartPage( container, new LocalizationEngine(localizationEngineSupport, "model", "de")); assertTrue(x, x.contains(szenario.getId())); htmlChecker.checkHtmlString(x); }
@Test public void testGenerateTasks_RevisedRegistrationReadyForApproval() throws Exception { RevisedInvestigatorRegistration registration = RegistrationFactory.getInstance().createRevisedInvestigatorRegistration(); registration.setStatus(ACCEPTED); setUpMockRegistrationServiceToReturnRegistration(registration); registration.getProtocol().setSponsor(sponsorOrganization); List<Task> tasks = generator.generateTasks(sponsor, groupNames); assertTrue(tasks.isEmpty()); }
@Test public void assertWorkspaceExistsWithOnlyName() throws Exception { when(server.execute(isA(MaskedArgumentListBuilder.class))) .thenReturn( new StringReader( "--------- -------------- -------- ----------------------------------------------------------------------------------------------------------\n" + "\n" + "name1 SND\\redsolo_cp COMPUTER\n")); Workspaces workspaces = new Workspaces(server); assertTrue("The workspace was reported as non existant", workspaces.exists("name1")); }
@Test public void keepsOldChecksumsInTheCache() throws IOException, TmcCoreException { try (FileWriter writer = new FileWriter(cache)) { writer.write( "{\"test-course\":{\"kissa\":\"qwerty\",\"asdf2\":\"aijw9\"},\"test-course2\":{\"ankka\":\"22222\"}}"); } ExerciseDownloader mock = Mockito.mock(ExerciseDownloader.class); Mockito.when(mock.createCourseFolder(anyString(), anyString())).thenReturn(""); Mockito.when(mock.handleSingleExercise(any(Exercise.class), anyString())).thenReturn(true); Course course = new Course(); course.setName("test-course"); course.setExercises( new ExerciseBuilder() .withExercise("kissa", 2, "eujwuc") .withExercise("asdf", 793, "alnwnec") .withExercise("ankka", 88, "abcdefg") .build()); parser = Mockito.mock(TmcJsonParser.class); Mockito.when(parser.getCourse(anyInt())).thenReturn(Optional.of(course)); DownloadExercises dl = new DownloadExercises(mock, "", "8", cache, settings, parser); dl.call(); String json = FileUtils.readFileToString(cache); Type typeOfHashMap = new TypeToken<Map<String, Map<String, String>>>() {}.getType(); Map<String, Map<String, String>> checksums = new Gson().fromJson(json, typeOfHashMap); assertNotNull(checksums); assertTrue(checksums.containsKey("test-course")); assertTrue(checksums.containsKey("test-course2")); assertTrue(checksums.get("test-course").containsKey("kissa")); assertTrue(checksums.get("test-course").containsKey("asdf")); assertTrue(checksums.get("test-course").containsKey("ankka")); assertEquals("eujwuc", checksums.get("test-course").get("kissa")); assertEquals("alnwnec", checksums.get("test-course").get("asdf")); assertEquals("aijw9", checksums.get("test-course").get("asdf2")); assertEquals("22222", checksums.get("test-course2").get("ankka")); }
@Test public void testGenerateTasks_AcceptedRegistrationWithUnAcceptedSubinvestigatorRegistration() throws Exception { InvestigatorRegistration registration = RegistrationFactory.getInstance().createInvestigatorRegistration(ACCEPTED); RegistrationFactory.getInstance().createSubinvestigatorRegistration(registration); setUpMockRegistrationServiceToReturnRegistration(registration); registration.getProtocol().setSponsor(sponsorOrganization); List<Task> tasks = generator.generateTasks(sponsor, groupNames); assertTrue(tasks.isEmpty()); }
@Test public void testGenerateTasks_CtepSponsor() throws Exception { Set<String> groupNames = Sets.newHashSet(); sponsor.getSponsorRoles().clear(); Organization ctepSponsor = new Organization(); sponsor.addSponsorRepresentativeRole(ctepSponsor); when(mockSponsorService.getSponsorOrganizationWithAnnualRegistrations()) .thenReturn(ctepSponsor); List<Task> tasks = generator.generateTasks(sponsor, groupNames); assertTrue(tasks.isEmpty()); }
@Test public void testMigrate_ItemWithTemplate() { Item item = mock(Item.class); doReturn(true).when(templateMigrator).migrate(item); assertTrue(migrator.migrate(item)); verify(projectMigrator, never()).migrate(any(AbstractProject.class)); verify(jobMigrator, never()).migrate(any(Job.class)); verify(templateMigrator).migrate(eq(item)); }
@Test public void renderAvatarShouldNotReturnNotModifiedAvatarInResponse() throws IOException, NotFoundException { JCUser user = getUser(); user.setAvatar(validAvatar); user.setAvatarLastModificationTime(new DateTime(0)); when(userService.get(anyLong())).thenReturn(user); MockHttpServletResponse response = new MockHttpServletResponse(); MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader(avatarController.IF_MODIFIED_SINCE_HEADER, new Date(1000)); avatarController.renderAvatar(request, response, 0L); assertEquals(response.getStatus(), HttpServletResponse.SC_NOT_MODIFIED); assertNotSame(response.getContentAsByteArray(), validAvatar); assertEquals(response.getHeader("Pragma"), "public"); List<String> cacheControlHeaders = response.getHeaders("Cache-Control"); assertTrue(cacheControlHeaders.contains("public")); assertTrue(cacheControlHeaders.contains("must-revalidate")); assertTrue(cacheControlHeaders.contains("max-age=0")); assertNotNull(response.getHeader("Expires")); // System.currentTimeMillis() is used assertNotNull(response.getHeader("Last-Modified")); // depends on current timezone }
@Test public void assertWorkspaceIsDeletedFromMap() throws Exception { when(server.execute(isA(MaskedArgumentListBuilder.class))).thenReturn(new StringReader("")); Workspaces workspaces = new Workspaces(server); // Populate the map in test object assertFalse( "The workspace was reported as existant", workspaces.exists(new Workspace(server, "name"))); Workspace workspace = workspaces.newWorkspace("name"); assertTrue( "The workspace was reported as non existant", workspaces.exists(new Workspace(server, "name"))); workspaces.deleteWorkspace(workspace); assertFalse("The workspace was reported as existant", workspaces.exists(workspace)); }
@Test public void testDowloadingWithProgress() throws Exception { CoreTestSettings settings1 = createSettingsAndWiremock(); ProgressObserver observerMock = Mockito.mock(ProgressObserver.class); String folder = System.getProperty("user.dir") + "/testResources/"; ListenableFuture<List<Exercise>> download = core.downloadExercises(folder, "35", settings1, observerMock); List<Exercise> exercises = download.get(); String exercisePath = folder + "2013_ohpeJaOhja/viikko1/Viikko1_001.Nimi"; assertEquals(exercises.size(), 153); assertTrue(new File(exercisePath).exists()); FileUtils.deleteDirectory(new File(exercisePath)); assertFalse(new File(exercisePath).exists()); Mockito.verify(observerMock, times(153)).progress(anyDouble(), anyString()); }
@Test public void downloadAllExercises() throws Exception { CoreTestSettings settings1 = createSettingsAndWiremock(); String folder = System.getProperty("user.dir") + "/testResources/"; ListenableFuture<List<Exercise>> download = core.downloadExercises(folder, "35", settings1, null); List<Exercise> exercises = download.get(); String exercisePath = folder + "2013_ohpeJaOhja/viikko1/Viikko1_001.Nimi"; assertEquals(exercises.size(), 153); assertTrue(new File(exercisePath).exists()); FileUtils.deleteDirectory(new File(exercisePath)); assertFalse(new File(exercisePath).exists()); }
@Test public void testValidateCollectionBothInvalid() { when(config.getBoolean(eq(ConfigProperties.STANDALONE))).thenReturn(false); List<ContentOverride> overrides = new LinkedList<ContentOverride>(); overrides.add(new ContentOverride("label", "baseurl", "value")); overrides.add(new ContentOverride("other label", "name", "other value")); try { validator.validate(overrides); fail("Expected exception \"BadRequestException\" was not thrown."); } catch (BadRequestException bre) { assertTrue( bre.getMessage() .matches("^Not allowed to override values for: (?:baseurl, name|name, baseurl)")); } }
@Test public void when_token_but_scope_is_null_return_true() throws Exception { // GIVEN String endpointScope = null; String tokenContent = "{\"tokenType\":\"599\",\"scope\":\"basic other\"," + "\"accessToken\":\"da96c8141bcda91be65db4adbc8fafe77d116c88caacb8de404c0654c16c6620\"," + "\"expiresIn\":\"Bearer\",\"userId\":null," + "\"refreshToken\":\"cb2e2e068447913d0c97f79f888f6e2882bfcb569325a9ad9e9b52937b06e547\"}"; // WHEN boolean result = AccessTokenValidator.validateTokenScope(tokenContent, endpointScope); // THEN assertTrue(result); }