@Test public void adhocIMChat6() throws JsonGenerationException, JsonMappingException, IOException { Setup.startTest("Checking that User 1 has received a chat message"); receiveMessageStatusURL = INVALID; String url = (Setup.channelURL[1].split("username\\=")[0]) + "username="******"notificationList.messageNotification.chatMessage.text", Matchers.hasItem("how are you"), "notificationList.messageNotification.sessionId", Matchers.hasItem("adhoc"), "notificationList.messageNotification.messageId", Matchers.notNullValue(), "notificationList.messageNotification.senderAddress", Matchers.hasItem(Setup.TestUser2Contact), "notificationList.messageNotification.link", Matchers.notNullValue()) .post(url); System.out.println("Response = " + response.getStatusCode() + " / " + response.asString()); receiveMessageStatusURL = response.jsonPath().getString("notificationList.messageNotification[0].link[0].href"); System.out.println("message status URL = " + receiveMessageStatusURL); Setup.endTest(); }
public void testClusterHealth() throws IOException { ClusterState clusterState = ClusterState.builder(ClusterName.CLUSTER_NAME_SETTING.getDefault(Settings.EMPTY)).build(); int pendingTasks = randomIntBetween(0, 200); int inFlight = randomIntBetween(0, 200); int delayedUnassigned = randomIntBetween(0, 200); TimeValue pendingTaskInQueueTime = TimeValue.timeValueMillis(randomIntBetween(1000, 100000)); ClusterHealthResponse clusterHealth = new ClusterHealthResponse( "bla", new String[] {MetaData.ALL}, clusterState, pendingTasks, inFlight, delayedUnassigned, pendingTaskInQueueTime); clusterHealth = maybeSerialize(clusterHealth); assertClusterHealth(clusterHealth); assertThat(clusterHealth.getNumberOfPendingTasks(), Matchers.equalTo(pendingTasks)); assertThat(clusterHealth.getNumberOfInFlightFetch(), Matchers.equalTo(inFlight)); assertThat(clusterHealth.getDelayedUnassignedShards(), Matchers.equalTo(delayedUnassigned)); assertThat(clusterHealth.getTaskMaxWaitingTime().millis(), is(pendingTaskInQueueTime.millis())); assertThat( clusterHealth.getActiveShardsPercent(), is(allOf(greaterThanOrEqualTo(0.0), lessThanOrEqualTo(100.0)))); }
private void checkExceptions(String script) { try { SearchResponse sr = client() .prepareSearch("test") .setQuery(QueryBuilders.matchAllQuery()) .addScriptField("tvtest", script) .execute() .actionGet(); assertThat(sr.getHits().hits().length, equalTo(0)); ShardSearchFailure[] shardFails = sr.getShardFailures(); for (ShardSearchFailure fail : shardFails) { assertThat( fail.reason() .indexOf( "Cannot iterate twice! If you want to iterate more that once, add _CACHE explicitly."), Matchers.greaterThan(-1)); } } catch (SearchPhaseExecutionException ex) { assertThat( "got " + ex.getDetailedMessage(), ex.getDetailedMessage() .indexOf( "Cannot iterate twice! If you want to iterate more that once, add _CACHE explicitly."), Matchers.greaterThan(-1)); } }
@Test public void testAfterPaneWithFixedWindow() throws Exception { Duration windowDuration = Duration.millis(10); ReduceFnTester<Integer, Iterable<Integer>, IntervalWindow> tester = ReduceFnTester.nonCombining( FixedWindows.of(windowDuration), AfterPane.<IntervalWindow>elementCountAtLeast(2), AccumulationMode.DISCARDING_FIRED_PANES, Duration.millis(100)); tester.injectElements( TimestampedValue.of(1, new Instant(1)), // first in window [0, 10) TimestampedValue.of(2, new Instant(9))); assertThat( tester.extractOutput(), Matchers.contains( WindowMatchers.isSingleWindowedValue(Matchers.containsInAnyOrder(1, 2), 1, 0, 10))); // This element belongs in the window that has already fired. It should not be re-output because // that trigger (which was one-time) has already gone off. tester.injectElements(TimestampedValue.of(6, new Instant(2))); assertThat(tester.extractOutput(), Matchers.emptyIterable()); assertTrue(tester.isMarkedFinished(new IntervalWindow(new Instant(0), new Instant(10)))); assertFalse(tester.isMarkedFinished(new IntervalWindow(new Instant(10), new Instant(20)))); tester.assertHasOnlyGlobalAndFinishedSetsFor( new IntervalWindow(new Instant(0), new Instant(10))); }
/** * Cacheable can cache static calls. * * @throws Exception If something goes wrong */ @Test public void cachesSimpleStaticCall() throws Exception { final String first = CacheableTest.Foo.staticGet(); MatcherAssert.assertThat(first, Matchers.equalTo(CacheableTest.Foo.staticGet())); CacheableTest.Foo.staticFlush(); MatcherAssert.assertThat(CacheableTest.Foo.staticGet(), Matchers.not(Matchers.equalTo(first))); }
@Test public void testFallThrough() throws Exception { HandlerList list = new HandlerList(); _server.setHandler(list); ServletContextHandler root = new ServletContextHandler(list, "/", ServletContextHandler.SESSIONS); ServletHandler servlet = root.getServletHandler(); servlet.setEnsureDefaultServlet(false); servlet.addServletWithMapping(HelloServlet.class, "/hello/*"); list.addHandler( new AbstractHandler() { @Override public void handle( String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.sendError(404, "Fell Through"); } }); _server.start(); String response = _connector.getResponses("GET /hello HTTP/1.0\r\n\r\n"); Assert.assertThat(response, Matchers.containsString("200 OK")); response = _connector.getResponses("GET /other HTTP/1.0\r\n\r\n"); Assert.assertThat(response, Matchers.containsString("404 Fell Through")); }
public Map<String, Path> buildMultipleAndReturnOutputs(String... args) throws IOException { // Add in `--show-output` to the build, so we can parse the output paths after the fact. ImmutableList<String> buildArgs = ImmutableList.<String>builder().add("--show-output").add(args).build(); ProjectWorkspace.ProcessResult buildResult = runBuckBuild(buildArgs.toArray(new String[buildArgs.size()])); buildResult.assertSuccess(); // Grab the stdout lines, which have the build outputs. List<String> lines = Splitter.on(CharMatcher.anyOf(System.lineSeparator())) .trimResults() .omitEmptyStrings() .splitToList(buildResult.getStdout()); // Skip the first line, which is just "The outputs are:". assertThat(lines.get(0), Matchers.equalTo("The outputs are:")); lines = lines.subList(1, lines.size()); Splitter lineSplitter = Splitter.on(' ').trimResults(); ImmutableMap.Builder<String, Path> builder = ImmutableMap.builder(); for (String line : lines) { List<String> fields = lineSplitter.splitToList(line); assertThat(fields, Matchers.hasSize(2)); builder.put(fields.get(0), getPath(fields.get(1))); } return builder.build(); }
@Test public void shouldAllowToNotResetStateBeforeScenario() throws Throwable { // Given StoryReporter reporter = mock(ConcurrentStoryReporter.class); Step pendingStep = mock(Step.class); when(pendingStep.perform(null)).thenReturn(pending("pendingStep")); Step secondStep = mockSuccessfulStep("secondStep"); StepCollector collector = mock(StepCollector.class); CandidateSteps mySteps = new Steps(); Scenario scenario1 = new Scenario(); Scenario scenario2 = new Scenario(); when(collector.collectScenarioSteps(asList(mySteps), scenario1, parameters)) .thenReturn(asList(pendingStep)); when(collector.collectScenarioSteps(asList(mySteps), scenario2, parameters)) .thenReturn(asList(secondStep)); Story story = new Story(asList(scenario1, scenario2)); givenStoryWithNoBeforeOrAfterSteps(story, false, collector, mySteps); // When StoryRunner runner = new StoryRunner(); Configuration configuration = configurationWith(reporter, collector); configuration.storyControls().doResetStateBeforeScenario(false); runner.run(configuration, asList(mySteps), story); // Then verify(pendingStep).perform(Matchers.<UUIDExceptionWrapper>any()); verify(secondStep).doNotPerform(Matchers.<UUIDExceptionWrapper>any()); verify(secondStep, never()).perform(Matchers.<UUIDExceptionWrapper>any()); }
@Test public void shouldAllowToNotResetStateBeforeStory() throws Throwable { // Given StoryReporter reporter = mock(ConcurrentStoryReporter.class); Step failedStep = mock(Step.class, "failedStep"); when(failedStep.perform(null)) .thenReturn( failed( "before stories", new UUIDExceptionWrapper(new RuntimeException("BeforeStories fail")))); Step pendingStep = mock(Step.class, "pendingStep"); when(pendingStep.perform(null)).thenReturn(pending("pendingStep")); StepCollector collector = mock(StepCollector.class); CandidateSteps mySteps = new Steps(); Scenario scenario1 = new Scenario(); List<CandidateSteps> candidateSteps = asList(mySteps); when(collector.collectBeforeOrAfterStoriesSteps(candidateSteps, Stage.BEFORE)) .thenReturn(asList(failedStep)); when(collector.collectScenarioSteps(candidateSteps, scenario1, parameters)) .thenReturn(asList(pendingStep)); Story story = new Story(asList(scenario1)); givenStoryWithNoBeforeOrAfterSteps(story, false, collector, mySteps); // When StoryRunner runner = new StoryRunner(); Configuration configuration = configurationWith(reporter, collector); configuration.storyControls().doResetStateBeforeStory(false).doResetStateBeforeScenario(false); runner.runBeforeOrAfterStories(configuration, candidateSteps, Stage.BEFORE); runner.run(configuration, candidateSteps, story); // Then verify(failedStep).perform(Matchers.<UUIDExceptionWrapper>any()); verify(pendingStep).perform(Matchers.<UUIDExceptionWrapper>any()); }
@Test public void testPlayersGetNewStatus() throws com.yazino.game.api.GameException { whenGameStart(); command = commandFrom(PLAYER1_ID); com.yazino.game.api.GamePlayer p1 = new com.yazino.game.api.GamePlayer(PLAYER1_ID, SESSION_ID, ""); com.yazino.game.api.GamePlayer p2 = new com.yazino.game.api.GamePlayer(PLAYER2_ID, SESSION_ID, ""); table.setCurrentGame(gameStatus1); whenPlayers(p1, p2); when(gameRules.getObservableStatus(gameStatus1, getContextFor(p1, false, table.getIncrement()))) .thenReturn(new PrintlnStatus()); when(gameRules.getObservableStatus(gameStatus1, getContextFor(p2, true, table.getIncrement()))) .thenReturn(new PrintlnStatus()); final com.yazino.game.api.ExecutionResult result = new com.yazino.game.api.ExecutionResult.Builder(gameRules, gameStatus1) .scheduledEvents(emptyEvents) .build(); when(gameRules.execute( isA(com.yazino.game.api.ExecutionContext.class), eq(command.toCommand(PLAYER_NAME)))) .thenReturn(result); final List<HostDocument> hostDocuments = executeCommand(); // table.lastGameChanges? assertThat(hostDocuments.size(), is(equalTo(2))); assertThat( (GameStatusHostDocument) hostDocuments.get(0), Matchers.isA(GameStatusHostDocument.class)); assertThat( (GameStatusHostDocument) hostDocuments.get(1), Matchers.isA(GameStatusHostDocument.class)); }
private Step mockSuccessfulStep(String result) { Step step = mock(Step.class, result); when(step.perform(Matchers.<UUIDExceptionWrapper>any())).thenReturn(successful(result)); when(step.doNotPerform(Matchers.<UUIDExceptionWrapper>any())) .thenReturn(notPerformed("successfulStep")); return step; }
@Test public void testEquivalent() throws ResourceNotFoundException { Sensor newSensor = Mockito.mock(Sensor.class); Map<String, Object> props = new HashMap<>(); props.put("fuelType", "diesel"); props.put("constructionYear", 2015); props.put("engineDisplacement", 1234); props.put("model", "Dito"); props.put("manufacturer", "Vito"); Mockito.when(newSensor.getProperties()).thenReturn(props); SensorDao dao = createDao(); CarSimilarityServiceImpl service = new CarSimilarityServiceImpl(dao); CarSimilarityServiceImpl serviceMock = Mockito.spy(service); serviceMock.setSimilarityDefinition("/car-similarity-test.json"); Sensor equi = serviceMock.resolveEquivalent(newSensor); Assert.assertThat(equi, Matchers.is(oldSensor)); props.put("manufacturer", "vito mobile "); Sensor similar = serviceMock.resolveEquivalent(newSensor); Assert.assertThat(similar, Matchers.is(oldSensor)); Mockito.verify(serviceMock, Mockito.times(1)) .isManufacturerSimilar(Mockito.any(String.class), Mockito.any(String.class)); }
@Test public void testArgsWithLocationMacroAffectDependenciesAndExpands() throws Exception { BuildRuleResolver resolver = new BuildRuleResolver(TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer()); SourcePathResolver pathResolver = new SourcePathResolver(resolver); BuildRule shBinaryRule = new ShBinaryBuilder(BuildTargetFactory.newInstance("//:my_exe")) .setMain(new FakeSourcePath("bin/exe")) .build(resolver); BuildRule exportFileRule = ExportFileBuilder.newExportFileBuilder(BuildTargetFactory.newInstance("//:file")) .setSrc(new FakeSourcePath("file.txt")) .build(resolver); WorkerToolBuilder workerToolBuilder = WorkerToolBuilder.newWorkerToolBuilder(BuildTargetFactory.newInstance("//:worker_rule")) .setExe(shBinaryRule.getBuildTarget()) .setArgs("--input $(location //:file)"); WorkerTool workerTool = (WorkerTool) workerToolBuilder.build(resolver); assertThat( workerToolBuilder.findImplicitDeps(), Matchers.hasItem(exportFileRule.getBuildTarget())); assertThat(workerTool.getDeps(), Matchers.hasItems(shBinaryRule, exportFileRule)); assertThat(workerTool.getRuntimeDeps(), Matchers.hasItems(shBinaryRule, exportFileRule)); assertThat( workerTool.getArgs(), Matchers.containsString( pathResolver .getAbsolutePath(new BuildTargetSourcePath(exportFileRule.getBuildTarget())) .toString())); }
@Test public void testCreateWorkerTool() throws NoSuchBuildTargetException { BuildRuleResolver resolver = new BuildRuleResolver(TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer()); BuildRule shBinaryRule = new ShBinaryBuilder(BuildTargetFactory.newInstance("//:my_exe")) .setMain(new FakeSourcePath("bin/exe")) .build(resolver); BuildRule workerRule = WorkerToolBuilder.newWorkerToolBuilder(BuildTargetFactory.newInstance("//:worker_rule")) .setExe(shBinaryRule.getBuildTarget()) .setArgs("arg1 arg2") .build(resolver); assertThat( "getBinaryBuildRule should return the build rule supplied in the definition.", shBinaryRule, Matchers.equalToObject(((WorkerTool) workerRule).getBinaryBuildRule())); assertThat( "getArgs should return the args string supplied in the definition.", "arg1 arg2", Matchers.is(((WorkerTool) workerRule).getArgs())); }
@Test public void testPutFacilityUuid() throws Exception { OrganisationUnit organisationUnit = createOrganisationUnit('A'); manager.save(organisationUnit); Facility facility = new OrganisationUnitToFacilityConverter().convert(organisationUnit); facility.setName("FacilityB"); facility.setActive(false); MockHttpSession session = getSession("ALL"); mvc.perform( put("/fred/v1/facilities/" + organisationUnit.getUuid()) .content(objectMapper.writeValueAsString(facility)) .session(session) .contentType(MediaType.APPLICATION_JSON)) .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.uuid", Matchers.notNullValue())) .andExpect(jsonPath("$.name").value("FacilityB")) .andExpect(jsonPath("$.active").value(false)) .andExpect(jsonPath("$.createdAt", Matchers.notNullValue())) .andExpect(jsonPath("$.updatedAt", Matchers.notNullValue())) .andExpect(header().string("ETag", Matchers.notNullValue())) .andExpect(status().isOk()); }
@Test public void testGetByIdOrNull() throws Exception { assertThat(service.getByIdOrNull(new TransUnitId(2)), Matchers.equalTo(data.get(1))); // not in current page assertThat(service.getByIdOrNull(new TransUnitId(99)), Matchers.nullValue()); }
@Test public void canGetProjects() { Project[] projects = client.getProjects(); assertThat(projects, Matchers.arrayWithSize(1)); assertThat(projects[0].getId(), Matchers.equalTo("about-fedora")); }
/** @see DATAREST-609 */ @Test public void addsSelfAndSingleResourceLinkToResourceByDefault() throws Exception { Projector projector = mock(Projector.class); when(projector.projectExcerpt(anyObject())).thenAnswer(new ReturnsArgumentAt(0)); PersistentEntityResourceAssembler assembler = new PersistentEntityResourceAssembler( entities, projector, associations, new DefaultSelfLinkProvider( entities, entityLinks, Collections.<EntityLookup<?>>emptyList())); User user = new User(); user.id = BigInteger.valueOf(4711); PersistentEntityResource resource = assembler.toResource(user); Links links = new Links(resource.getLinks()); assertThat(links, is(Matchers.<Link>iterableWithSize(2))); assertThat(links.getLink("self").getVariables(), is(Matchers.empty())); assertThat(links.getLink("user").getVariableNames(), is(hasItem("projection"))); }
@Test public void testDefaultRecoverAfterTime() throws IOException { // check that the default is not set GatewayService service = createService(Settings.builder()); assertNull(service.recoverAfterTime()); // ensure default is set when setting expected_nodes service = createService(Settings.builder().put("gateway.expected_nodes", 1)); assertThat( service.recoverAfterTime(), Matchers.equalTo(GatewayService.DEFAULT_RECOVER_AFTER_TIME_IF_EXPECTED_NODES_IS_SET)); // ensure default is set when setting expected_data_nodes service = createService(Settings.builder().put("gateway.expected_data_nodes", 1)); assertThat( service.recoverAfterTime(), Matchers.equalTo(GatewayService.DEFAULT_RECOVER_AFTER_TIME_IF_EXPECTED_NODES_IS_SET)); // ensure default is set when setting expected_master_nodes service = createService(Settings.builder().put("gateway.expected_master_nodes", 1)); assertThat( service.recoverAfterTime(), Matchers.equalTo(GatewayService.DEFAULT_RECOVER_AFTER_TIME_IF_EXPECTED_NODES_IS_SET)); // ensure settings override default TimeValue timeValue = TimeValue.timeValueHours(3); // ensure default is set when setting expected_nodes service = createService( Settings.builder() .put("gateway.expected_nodes", 1) .put("gateway.recover_after_time", timeValue.toString())); assertThat(service.recoverAfterTime().millis(), Matchers.equalTo(timeValue.millis())); }
@Test @SuppressWarnings("unchecked") public void testGetTimeSinceLastMeasurement() throws Exception { long sleepTime = 20L; // fill history with the same value. long now = System.nanoTime() - 2 * sleepTime * 1000000; for (int i = 0; i < TestUtils.getPropertyValue(history, "retention", Integer.class); i++) { history.success(now); } final Deque<Long> times = TestUtils.getPropertyValue(history, "times", Deque.class); assertEquals(Long.valueOf(now), times.peekFirst()); assertEquals(Long.valueOf(now), times.peekLast()); // increment just so we'll have a different value between first and last history.success(System.nanoTime() - sleepTime * 1000000); assertNotEquals(times.peekFirst(), times.peekLast()); /* * We've called Thread.sleep twice with the same value in quick * succession. If timeSinceLastSend is pulling off the correct end of * the queue, then we should be closer to the sleep time than we are to * 2 x sleepTime, but we should definitely be greater than the sleep * time. */ double timeSinceLastMeasurement = history.getTimeSinceLastMeasurement(); assertThat(timeSinceLastMeasurement, Matchers.greaterThan((double) (sleepTime / 100))); assertThat(timeSinceLastMeasurement, Matchers.lessThanOrEqualTo(1.5 * sleepTime / 100)); }
@Test public void testAfterPaneWithGlobalWindowsAndCombining() throws Exception { Duration windowDuration = Duration.millis(10); ReduceFnTester<Integer, Integer, IntervalWindow> tester = ReduceFnTester.combining( FixedWindows.of(windowDuration), AfterPane.<IntervalWindow>elementCountAtLeast(2), AccumulationMode.DISCARDING_FIRED_PANES, new SumIntegerFn().<String>asKeyedFn(), VarIntCoder.of(), Duration.millis(100)); tester.injectElements( TimestampedValue.of(1, new Instant(1)), TimestampedValue.of(2, new Instant(9))); assertThat( tester.extractOutput(), Matchers.contains(WindowMatchers.isSingleWindowedValue(Matchers.equalTo(3), 1, 0, 10))); // This element should not be output because that trigger (which was one-time) has already // gone off. tester.injectElements(TimestampedValue.of(6, new Instant(2))); assertThat(tester.extractOutput(), Matchers.emptyIterable()); assertTrue(tester.isMarkedFinished(new IntervalWindow(new Instant(0), new Instant(10)))); assertFalse(tester.isMarkedFinished(new IntervalWindow(new Instant(10), new Instant(20)))); tester.assertHasOnlyGlobalAndFinishedSetsFor( new IntervalWindow(new Instant(0), new Instant(10))); }
@Test public void ruleKeyChangesIfInputContentsFromPathSourcePathInRuleKeyAppendableChanges() { BuildRuleResolver resolver = new BuildRuleResolver(TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer()); SourcePathResolver pathResolver = new SourcePathResolver(resolver); final FakeProjectFilesystem filesystem = new FakeProjectFilesystem(); final Path output = Paths.get("output"); BuildRuleParams params = new FakeBuildRuleParamsBuilder("//:rule").setProjectFilesystem(filesystem).build(); BuildRule rule = new NoopBuildRule(params, pathResolver) { @AddToRuleKey RuleKeyAppendableWithInput input = new RuleKeyAppendableWithInput(new PathSourcePath(filesystem, output)); }; // Build a rule key with a particular hash set for the output for the above rule. FakeFileHashCache hashCache = new FakeFileHashCache(ImmutableMap.of(filesystem.resolve(output), HashCode.fromInt(0))); RuleKey inputKey1 = new InputBasedRuleKeyBuilderFactory(0, hashCache, pathResolver).build(rule); // Now, build a rule key with a different hash for the output for the above rule. hashCache = new FakeFileHashCache(ImmutableMap.of(filesystem.resolve(output), HashCode.fromInt(1))); RuleKey inputKey2 = new InputBasedRuleKeyBuilderFactory(0, hashCache, pathResolver).build(rule); assertThat(inputKey1, Matchers.not(Matchers.equalTo(inputKey2))); }
/** * Cacheable can clean cache after timeout. * * @throws Exception If something goes wrong */ @Test public void cleansCacheWhenExpired() throws Exception { final CacheableTest.Foo foo = new CacheableTest.Foo(1L); final String first = foo.get().toString(); TimeUnit.SECONDS.sleep((long) Tv.FIVE); MatcherAssert.assertThat(foo.get().toString(), Matchers.not(Matchers.equalTo(first))); }
@Test public void ruleKeyChangesIfInputContentsFromPathSourceChanges() throws Exception { BuildRuleResolver resolver = new BuildRuleResolver(TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer()); SourcePathResolver pathResolver = new SourcePathResolver(resolver); FakeProjectFilesystem filesystem = new FakeProjectFilesystem(); Path output = Paths.get("output"); BuildRule rule = ExportFileBuilder.newExportFileBuilder(BuildTargetFactory.newInstance("//:rule")) .setOut("out") .setSrc(new PathSourcePath(filesystem, output)) .build(resolver, filesystem); // Build a rule key with a particular hash set for the output for the above rule. FakeFileHashCache hashCache = new FakeFileHashCache(ImmutableMap.of(filesystem.resolve(output), HashCode.fromInt(0))); RuleKey inputKey1 = new InputBasedRuleKeyBuilderFactory(0, hashCache, pathResolver).build(rule); // Now, build a rule key with a different hash for the output for the above rule. hashCache = new FakeFileHashCache(ImmutableMap.of(filesystem.resolve(output), HashCode.fromInt(1))); RuleKey inputKey2 = new InputBasedRuleKeyBuilderFactory(0, hashCache, pathResolver).build(rule); assertThat(inputKey1, Matchers.not(Matchers.equalTo(inputKey2))); }
public void testEmptyAggregation() throws Exception { SearchResponse searchResponse = client() .prepareSearch("empty_bucket_idx") .setQuery(matchAllQuery()) .addAggregation( histogram("histo") .field("value") .interval(1L) .minDocCount(0) .subAggregation(nested("nested", "nested"))) .execute() .actionGet(); assertThat(searchResponse.getHits().getTotalHits(), equalTo(2L)); Histogram histo = searchResponse.getAggregations().get("histo"); assertThat(histo, Matchers.notNullValue()); Histogram.Bucket bucket = histo.getBuckets().get(1); assertThat(bucket, Matchers.notNullValue()); Nested nested = bucket.getAggregations().get("nested"); assertThat(nested, Matchers.notNullValue()); assertThat(nested.getName(), equalTo("nested")); assertThat(nested.getDocCount(), is(0L)); }
/** * TODO DOCUMENT ME! * * @throws Exception */ @Test public void testMentionedInCommit() throws Exception { MentionedInCommitStrategy strategy = new MentionedInCommitStrategy(); ChangeLogSet mockChangeSet = MockChangeLogUtil.mockChangeLogSet( new MockChangeLogUtil.MockChangeLog("FOO-101 first", "knork"), new MockChangeLogUtil.MockChangeLog("[BAR-102] with square brackets", "zark"), new MockChangeLogUtil.MockChangeLog("Fixed FOO-103 inbetween", "flarp"), new MockChangeLogUtil.MockChangeLog("Fixed BAR-104typo", "narf"), new MockChangeLogUtil.MockChangeLog( "FOO-101 again but, because FOO-101 was invalid, but FOO-105 not", "knork"), new MockChangeLogUtil.MockChangeLog("Invalid [foo-103] lowercase", "flarp"), new MockChangeLogUtil.MockChangeLog("No Valid Ticket", "build robot")); AbstractBuild mockBuild = mock(AbstractBuild.class); when(mockBuild.getChangeSet()).thenReturn(mockChangeSet); List<JiraCommit> commits = strategy.getJiraCommits( mockBuild, new StreamBuildListener(System.out, Charset.defaultCharset())); assertEquals(commits.size(), 6); assertThat( commits, hasItem(Matchers.<JiraCommit>hasProperty("jiraTicket", equalTo("FOO-101")))); assertThat( commits, hasItem(Matchers.<JiraCommit>hasProperty("jiraTicket", equalTo("BAR-102")))); assertThat( commits, hasItem(Matchers.<JiraCommit>hasProperty("jiraTicket", equalTo("FOO-103")))); assertThat( commits, hasItem(Matchers.<JiraCommit>hasProperty("jiraTicket", equalTo("BAR-104")))); assertThat( commits, hasItem(Matchers.<JiraCommit>hasProperty("jiraTicket", equalTo("FOO-105")))); }
@JavascriptEnabled @Ignore( value = {SAFARI, MARIONETTE}, reason = " Safari: issue 4061. Other platforms: not properly tested") @Test public void testChangeEventIsFiredAppropriatelyWhenFocusIsLost() { driver.get(pages.javascriptPage); WebElement input = driver.findElement(By.id("changeable")); input.sendKeys("test"); moveFocus(); assertThat( driver.findElement(By.id("result")).getText().trim(), Matchers.<String>either(is("focus change blur")).or(is("focus blur change"))); input.sendKeys(Keys.BACK_SPACE, "t"); moveFocus(); // I weep. assertThat( driver.findElement(By.id("result")).getText().trim(), Matchers.<String>either(is("focus change blur focus blur")) .or(is("focus blur change focus blur")) .or(is("focus blur change focus blur change")) .or(is("focus change blur focus change blur"))); // What Chrome does }
@Test public void sockJsAttributesSupport() { loadBeanDefinitions("websocket-config-handlers-sockjs-attributes.xml"); SimpleUrlHandlerMapping handlerMapping = appContext.getBean(SimpleUrlHandlerMapping.class); assertNotNull(handlerMapping); SockJsHttpRequestHandler handler = (SockJsHttpRequestHandler) handlerMapping.getUrlMap().get("/test/**"); assertNotNull(handler); checkDelegateHandlerType(handler.getWebSocketHandler(), TestWebSocketHandler.class); SockJsService sockJsService = handler.getSockJsService(); assertNotNull(sockJsService); assertThat(sockJsService, Matchers.instanceOf(TransportHandlingSockJsService.class)); TransportHandlingSockJsService defaultSockJsService = (TransportHandlingSockJsService) sockJsService; assertThat( defaultSockJsService.getTaskScheduler(), Matchers.instanceOf(TestTaskScheduler.class)); assertThat( defaultSockJsService.getTransportHandlers().values(), Matchers.containsInAnyOrder( Matchers.instanceOf(XhrPollingTransportHandler.class), Matchers.instanceOf(XhrStreamingTransportHandler.class))); assertEquals("testSockJsService", defaultSockJsService.getName()); assertFalse(defaultSockJsService.isWebSocketEnabled()); assertFalse(defaultSockJsService.isSessionCookieNeeded()); assertEquals(2048, defaultSockJsService.getStreamBytesLimit()); assertEquals(256, defaultSockJsService.getDisconnectDelay()); assertEquals(1024, defaultSockJsService.getHttpMessageCacheSize()); assertEquals(20, defaultSockJsService.getHeartbeatTime()); }
@Test public void testCachedPut() throws Exception { HttpFields header = new HttpFields(); header.put("Connection", "Keep-Alive"); header.put("tRansfer-EncOding", "CHUNKED"); header.put("CONTENT-ENCODING", "gZIP"); ByteBuffer buffer = BufferUtil.allocate(1024); BufferUtil.flipToFill(buffer); HttpGenerator.putTo(header, buffer); BufferUtil.flipToFlush(buffer, 0); String out = BufferUtil.toString(buffer).toLowerCase(); Assert.assertThat( out, Matchers.containsString( (HttpHeader.CONNECTION + ": " + HttpHeaderValue.KEEP_ALIVE).toLowerCase())); Assert.assertThat( out, Matchers.containsString( (HttpHeader.TRANSFER_ENCODING + ": " + HttpHeaderValue.CHUNKED).toLowerCase())); Assert.assertThat( out, Matchers.containsString( (HttpHeader.CONTENT_ENCODING + ": " + HttpHeaderValue.GZIP).toLowerCase())); }
@Test public void sessionIMChatAccept23() throws JsonGenerationException, JsonMappingException, IOException { Setup.startTest("Checking that User 3 has received chat closed notification"); System.out.println("sessionID=" + sessionID); System.out.println("receiveSessionID=" + receiveSessionID); RestAssured.authentication = RestAssured.DEFAULT_AUTH; String url = (Setup.channelURL[3].split("username\\=")[0]) + "username="******"notificationList.chatEventNotification.eventType", Matchers.hasItem("SessionEnded"), "notificationList.chatEventNotification.sessionId", Matchers.hasItem(sessionID), "notificationList.chatEventNotification.link[0].rel", Matchers.hasItem("ChatSessionInformation")) .post(url); System.out.println("Response = " + response.getStatusCode() + " / " + response.asString()); Setup.endTest(); }