Java Examples for org.hamcrest.CoreMatchers

The following java examples will help you to understand the usage of org.hamcrest.CoreMatchers. These source code samples are taken from different open source projects.

Example 1
Project: roaster-master  File: JavaLocalClassTest.java View source code
@Test
public void testLocalClassMatch() {
    JavaClassSource source = Roaster.parse(JavaClassSource.class, getClass().getResourceAsStream("/org/jboss/forge/grammar/java/MockLocalClass.java"));
    Assert.assertFalse(source.isLocalClass());
    List<JavaSource<?>> nestedTypes = source.getNestedTypes();
    Assert.assertThat(nestedTypes.size(), equalTo(17));
    Assert.assertThat(nestedTypes.get(0), instanceOf(JavaInterface.class));
    Assert.assertThat(nestedTypes.subList(1, 17), everyItem(allOf(CoreMatchers.<JavaSource<?>>instanceOf(JavaClass.class), new IsLocalMatcher())));
}
Example 2
Project: detective-master  File: ConfigTest.java View source code
@Test
public void testSubConfig() {
    Config config = ConfigFactory.load("detective/core/common/unit-test-task-config.conf");
    assertThat(config.hasPath("tasks"), is(true));
    Config configLogin = config.getConfig("tasks.login");
    assertThat(configLogin, notNullValue());
    assertThat(configLogin.getString("url"), CoreMatchers.equalTo("localhost:8080/login_check"));
}
Example 3
Project: restfulie-java-master  File: FormEncodedTest.java View source code
@Test
public void shouldConcatenateParams() throws IOException {
    FormEncoded encoded = new FormEncoded();
    StringWriter writer = new StringWriter();
    Map<String, String> params = new HashMap<String, String>();
    params.put("name", "Guilherme");
    params.put("age", "29");
    encoded.marshal(params, writer, new DefaultRestClient());
    assertThat(writer.toString(), Matchers.anyOf(is(CoreMatchers.equalTo("name=Guilherme&age=29")), is(CoreMatchers.equalTo("age=29&name=Guilherme"))));
}
Example 4
Project: sandboxes-master  File: XmlConfigurationManipulation_Test.java View source code
@Test
public void addEachArtifactAsASystemProperty() throws Exception {
    List<BuildArtifact> buildArtifact = new ArrayList<BuildArtifact>();
    buildArtifact.add(DummyBuildArtifact.defaultArtifactAt("brot"));
    buildArtifact.add(DummyBuildArtifact.attachedArtifactWith("juhu", "asfdasd"));
    configurationTemplate.addArgumentsFor(buildArtifact);
    final Xpp3Dom[] dome = new Xpp3Dom[1];
    configurationTemplate.attachConfigurationTo(new ConfigurationSink() {

        @Override
        public void consume(Xpp3Dom dom) {
            dome[0] = dom;
        }
    });
    assertThat(dome[0].toString(), CoreMatchers.allOf(containsString("brot"), containsString("<name>maven.artifact.juhu</name>")));
}
Example 5
Project: droolsjbpm-integration-master  File: StandardjBPM5FluentTest.java View source code
@Test
public void testUsingImplicit() throws IOException {
    SimulationFluent f = new DefaultSimulationFluent();
    VariableContext<Person> pc = f.<Person>getVariableContext();
    List<String> imports = new ArrayList<String>();
    imports.add("org.hamcrest.MatcherAssert.assertThat");
    imports.add("org.hamcrest.CoreMatchers.is");
    imports.add("org.hamcrest.CoreMatchers.equalTo");
    imports.add("org.hamcrest.CoreMatchers.allOf");
    ReflectiveMatcherFactory rf = new ReflectiveMatcherFactory(imports);
    String str = "package org.drools.simulation.test\n" + "import " + Person.class.getName() + "\n" + "global java.util.List list\n" + "rule setTime\n" + "  when\n" + "  then\n" + "    list.add( kcontext.getKnowledgeRuntime().getSessionClock().getCurrentTime() );\n" + "end\n" + "rule updateAge no-loop\n" + "  when\n" + "    $p : Person()\n" + "  then\n" + "    list.add( kcontext.getKnowledgeRuntime().getSessionClock().getCurrentTime() );\n" + "    modify( $p ) {\n" + "      setAge( $p.getAge() + 10 )\n" + "    };\n" + "end\n";
    String strProcess = "<definitions id='Definition' " + "targetNamespace='http://www.jboss.org/drools' " + "typeLanguage='http://www.java.com/javaTypes' " + "expressionLanguage='http://www.mvel.org/2.0' " + "xmlns='http://www.omg.org/spec/BPMN/20100524/MODEL' " + "xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' " + "xsi:schemaLocation='http://www.omg.org/spec/BPMN/20100524/MODEL BPMN20.xsd' " + "xmlns:g='http://www.jboss.org/drools/flow/gpd' " + "xmlns:bpmndi='http://www.omg.org/spec/BPMN/20100524/DI' " + "xmlns:dc='http://www.omg.org/spec/DD/20100524/DC' " + "xmlns:di='http://www.omg.org/spec/DD/20100524/DI' " + "xmlns:tns='http://www.jboss.org/drools'>" + " <process id='DummyProcess' name='Sample Process'>" + "<startEvent id='_1' name='StartProcess' />" + "<scriptTask id='_2' name='Script 1' >" + "<script>System.out.println('Script 1 - Executing .. ');</script> " + "</scriptTask>" + "<scriptTask id='_3' name='Script 2' >" + "<script>System.out.println('Script 2 - Executing .. ');</script>" + "</scriptTask>" + "<endEvent id='_4' name='End' >" + "<terminateEventDefinition/>" + "</endEvent>" + "<sequenceFlow id='_1-_2' sourceRef='_1' targetRef='_2' />" + "<sequenceFlow id='_2-_3' sourceRef='_2' targetRef='_3' />" + "<sequenceFlow id='_3-_4' sourceRef='_3' targetRef='_4' />" + "</process>" + "</definitions>";
    ReleaseId releaseId = createKJarWithMultipleResources("org.test.KBase1", new String[] { str, strProcess }, new ResourceType[] { ResourceType.DRL, ResourceType.BPMN2 });
    List list = new ArrayList();
    VariableContext<?> vc = f.getVariableContext();
    // @formatter:off          
    f.newPath("init").newStep(0).newKieSession(releaseId, "org.test.KBase1.KSession1").setGlobal("list", list).set("list").startProcess("DummyProcess").fireAllRules().end().runSimulation();
// @formatter:on
}
Example 6
Project: enviroCar-app-master  File: ResponseParserTest.java View source code
@Test
public void testLambdaParsing() throws InvalidCommandResponseException, NoDataReceivedException, UnmatchedResponseException, AdapterSearchingException {
    ResponseParser responseParser = new ResponseParser();
    DataResponse response = responseParser.parse("412407FF0028".getBytes());
    Assert.assertThat(response.getPid(), CoreMatchers.is(PID.O2_LAMBDA_PROBE_1_VOLTAGE));
    Assert.assertThat(response.isComposite(), CoreMatchers.is(true));
    Number[] composites = response.getCompositeValues();
    Assert.assertThat(composites.length, CoreMatchers.is(2));
    //ER: byte A = 7, byte B = 255 --> ((7*256)+255)*2/65535
    Assert.assertThat(composites[0], CoreMatchers.is(((7 * 256) + 255) / 32768d));
    //Voltage: byte C = 0, byte D = 40--> ((0*256)+40)*8/65535
    Assert.assertThat(composites[1], CoreMatchers.is(((0 * 256) + 40) / 8192d));
}
Example 7
Project: variant-store-master  File: VariantUtilsTest.java View source code
@Test
public void testAddInfoToVariant() throws Exception {
    GAVariant variant = new GAVariant();
    String key = "key";
    String value = "value";
    VariantUtils.addInfo(variant, key, value);
    assertNotNull(variant.getInfo());
    assertThat(variant.getInfo(), instanceOf(Map.class));
    assertThat(variant.getInfo().get(key), CoreMatchers.<List<String>>is(Arrays.asList(value)));
    String key2 = "key2";
    String value2 = "value2";
    VariantUtils.addInfo(variant, key2, value2);
    assertThat(variant.getInfo().size(), is(2));
    assertThat(variant.getInfo().get(key), CoreMatchers.<List<String>>is(Arrays.asList(value)));
    assertThat(variant.getInfo().get(key2), CoreMatchers.<List<String>>is(Arrays.asList(value2)));
}
Example 8
Project: byte-buddy-master  File: SuperMethodCallTest.java View source code
@Test
@SuppressWarnings("unchecked")
public void testInstrumentedMethod() throws Exception {
    DynamicType.Loaded<Foo> loaded = new ByteBuddy().subclass(Foo.class).method(isDeclaredBy(Foo.class)).intercept(SuperMethodCall.INSTANCE).make().load(Foo.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER);
    assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0));
    assertThat(loaded.getLoaded().getDeclaredMethods().length, is(11));
    Foo instance = loaded.getLoaded().getDeclaredConstructor().newInstance();
    assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(Foo.class)));
    assertThat(instance, instanceOf(Foo.class));
    assertThat(loaded.getLoaded().getDeclaredMethod(methodName, methodParameterTypes).invoke(instance, methodArguments), (Matcher) matcher);
    instance.assertOnlyCall(methodName, methodArguments);
}
Example 9
Project: downlords-faf-client-master  File: FafServiceImplTest.java View source code
@Test
public void selectAvatar() throws Exception {
    URL url = new URL("http://example.com");
    instance.selectAvatar(new AvatarBean(url, "Description"));
    ArgumentCaptor<AvatarChangedEvent> eventCaptor = ArgumentCaptor.forClass(AvatarChangedEvent.class);
    verify(eventBus).post(eventCaptor.capture());
    AvatarBean avatar = eventCaptor.getValue().getAvatar();
    assertThat(avatar, not(CoreMatchers.nullValue()));
    assertThat(avatar.getUrl(), is(url));
    assertThat(avatar.getDescription(), is("Description"));
    verify(fafServerAccessor).selectAvatar(url);
}
Example 10
Project: furnace-cdi-master  File: ServiceLookupTest.java View source code
@SuppressWarnings("unchecked")
@Test
public void shouldResolveImpls() throws Exception {
    Imported<ServiceInterface> imported = registry.getServices(ServiceInterface.class);
    Assert.assertTrue(imported.isAmbiguous());
    Assert.assertEquals(3, Iterators.asList(imported).size());
    Assert.assertThat(imported, CoreMatchers.<ServiceInterface>hasItems(instanceOf(ServiceBean.class), instanceOf(AnotherServiceBean.class), instanceOf(SubServiceBean.class)));
}
Example 11
Project: geoserver-master  File: JMSCatalogModifyEventHandlerTest.java View source code
@Test
public void testCatalogModifyEventHandling() throws Exception {
    // create a catalog modify event that include properties of type catalog
    CatalogModifyEventImpl catalogModifyEvent = new CatalogModifyEventImpl();
    catalogModifyEvent.setPropertyNames(Arrays.asList("propertyA", "propertyB", "propertyC", "propertyD"));
    catalogModifyEvent.setOldValues(Arrays.asList("value", new CatalogImpl(), 50, null));
    catalogModifyEvent.setNewValues(Arrays.asList("new_value", new CatalogImpl(), null, new CatalogImpl()));
    // serialise the event and deserialize it
    JMSCatalogModifyEventHandlerSPI handler = new JMSCatalogModifyEventHandlerSPI(0, null, new XStream(), null);
    String serializedEvent = handler.createHandler().serialize(catalogModifyEvent);
    CatalogEvent newEvent = handler.createHandler().deserialize(serializedEvent);
    // check the deserialized event
    assertThat(newEvent, notNullValue());
    assertThat(newEvent, instanceOf(CatalogModifyEvent.class));
    CatalogModifyEvent newModifyEvent = (CatalogModifyEvent) newEvent;
    // check properties names
    assertThat(newModifyEvent.getPropertyNames().size(), is(2));
    assertThat(newModifyEvent.getPropertyNames(), CoreMatchers.hasItems("propertyA", "propertyC"));
    // check old values
    assertThat(newModifyEvent.getOldValues().size(), is(2));
    assertThat(newModifyEvent.getOldValues(), CoreMatchers.hasItems("value", 50));
    // check new values
    assertThat(newModifyEvent.getNewValues().size(), is(2));
    assertThat(newModifyEvent.getNewValues(), CoreMatchers.hasItems("new_value", null));
}
Example 12
Project: java-virtual-machine-master  File: SuperMethodCallTest.java View source code
@Test
@SuppressWarnings("unchecked")
public void testInstrumentedMethod() throws Exception {
    DynamicType.Loaded<Foo> loaded = new ByteBuddy().subclass(Foo.class).method(isDeclaredBy(Foo.class)).intercept(SuperMethodCall.INSTANCE).make().load(Foo.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER);
    assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0));
    assertThat(loaded.getLoaded().getDeclaredMethods().length, is(11));
    Foo instance = loaded.getLoaded().getDeclaredConstructor().newInstance();
    assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(Foo.class)));
    assertThat(instance, instanceOf(Foo.class));
    assertThat(loaded.getLoaded().getDeclaredMethod(methodName, methodParameterTypes).invoke(instance, methodArguments), (Matcher) matcher);
    instance.assertOnlyCall(methodName, methodArguments);
}
Example 13
Project: swingx-master  File: RectanglePainterTest.java View source code
@Test
@Override
public void testDefaults() {
    assertThat(p.getFilters().length, is(0));
    assertThat(p.getInterpolation(), is(AbstractPainter.Interpolation.NearestNeighbor));
    assertThat(p.isAntialiasing(), is(true));
    assertThat(p.isCacheable(), is(false));
    assertThat(p.isCacheCleared(), is(true));
    assertThat(p.isDirty(), is(false));
    assertThat(p.isInPaintContext(), is(false));
    assertThat(p.isVisible(), is(true));
    assertThat(p.shouldUseCache(), is(p.isCacheable()));
    AbstractLayoutPainter alp = (AbstractLayoutPainter) p;
    assertThat(alp.getHorizontalAlignment(), is(AbstractLayoutPainter.HorizontalAlignment.CENTER));
    assertThat(alp.getInsets(), is(new Insets(0, 0, 0, 0)));
    assertThat(alp.getVerticalAlignment(), is(AbstractLayoutPainter.VerticalAlignment.CENTER));
    assertThat(alp.isFillHorizontal(), is(true));
    assertThat(alp.isFillVertical(), is(true));
    AbstractAreaPainter aap = (AbstractAreaPainter) p;
    assertThat(aap.getAreaEffects(), is(new AreaEffect[0]));
    assertThat(aap.getBorderPaint(), CoreMatchers.<Paint>is(Color.BLACK));
    assertThat(aap.getBorderWidth(), is(1f));
    assertThat(aap.getFillPaint(), CoreMatchers.<Paint>is(Color.RED));
    assertThat(aap.getStyle(), is(AbstractAreaPainter.Style.BOTH));
    RectanglePainter rp = (RectanglePainter) p;
    assertThat(rp.getRoundHeight(), is(0));
    assertThat(rp.getRoundWidth(), is(0));
    assertThat(rp.isRounded(), is(false));
}
Example 14
Project: 99-problems-master  File: Problem4_1Test.java View source code
@Test
public void shouldDistributePlayersIntoTwoUnfairTeams() throws Exception {
    List<Player> players = Arrays.asList(new Player("a", 10), new Player("b", 7), new Player("c", 11), new Player("d", 2), new Player("e", 4), new Player("f", 15));
    List<List<Player>> teams = Problem4_1.teams(players);
    assertThat(teams.get(0), CoreMatchers.equalTo(Arrays.asList(new Player("d", 2), new Player("e", 4), new Player("b", 7))));
    assertThat(teams.get(1), CoreMatchers.equalTo(Arrays.asList(new Player("a", 10), new Player("c", 11), new Player("f", 15))));
}
Example 15
Project: camunda-bpm-needle-master  File: ProcessEngineTestWatcherTest.java View source code
@Test
@Deployment(resources = "test-process.bpmn")
public void should_deploy_and_start_process() {
    Assert.assertThat(processEngineTestWatcher.getDeploymentId(), CoreMatchers.notNullValue());
    final ProcessInstance processInstance = processEngineTestWatcher.getRuntimeService().startProcessInstanceByKey("test-process");
    Assert.assertThat(processInstance, CoreMatchers.notNullValue());
    Assert.assertThat(processEngineTestWatcher.getRuntimeService().createProcessInstanceQuery().active().list().size(), CoreMatchers.is(1));
}
Example 16
Project: core-ng-project-master  File: HTMLTemplateEngineTest.java View source code
@Test
public void process() {
    engine.add("test", "<html><img c:src=\"imageURL\"></html>", TestModel.class);
    TestModel model = new TestModel();
    model.imageURL = "http://domain/image.png";
    String html = engine.process("test", model);
    Assert.assertThat(html, CoreMatchers.containsString("<img src=http://domain/image.png>"));
}
Example 17
Project: deploy-plugin-master  File: PasswordProtectedAdapterCargoTest.java View source code
@Test
public void testDeserializeOldPlainPassword() {
    String plainPassword = "plain-password";
    String oldXml = "<hudson.plugins.deploy.glassfish.GlassFish3xAdapter><userName>manager</userName><password>" + plainPassword + "</password><home>/</home><hostname></hostname></hudson.plugins.deploy.glassfish.GlassFish3xAdapter>";
    XStream2 xs = new XStream2();
    PasswordProtectedAdapterCargo adapter = (PasswordProtectedAdapterCargo) xs.fromXML(oldXml);
    Assert.assertEquals(plainPassword, adapter.getPassword());
    String newXml = xs.toXML(adapter);
    Assert.assertThat("Password should be scrambled", newXml, CoreMatchers.not(JUnitMatchers.containsString(plainPassword)));
}
Example 18
Project: form-sql-builder-mysql-master  File: DefaultRuleSchemeGeneratorTest.java View source code
@Test
public void testGenerateRuleScheme() {
    DefaultRuleSchemeGenerator g = new DefaultRuleSchemeGenerator();
    Person form = new Person("ted", 22, "xiamen", 1);
    Map<String, Rule> m = g.generateRuleScheme(form);
    assertThat(m.get("name").getOp(), CoreMatchers.is(Operator.LIKE));
    assertThat(m.get("age").getRel(), CoreMatchers.is(Relation.AND));
}
Example 19
Project: Java-RSRepair-master  File: TestRepair.java View source code
@Test
public void testSampleProgram() throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    System.setOut(new PrintStream(baos));
    JRSRepair repair = JRSRepairMain.readConfigFile(new File("/Users/qhanam/Repositories/Java-RSRepair/sample/config/jrsrepair.properties"));
    repair.buildASTs();
    repair.repair();
    String output = baos.toString();
    Assert.assertThat(output, CoreMatchers.containsString("Compiled! Failed."));
    Assert.assertThat(output, CoreMatchers.containsString("Compiled! Passed!"));
}
Example 20
Project: junit-master  File: VerifierRuleTest.java View source code
@Test
public void usedErrorCollectorCheckSucceedsWithAssumptionViolatedExceptionShouldFail() {
    PrintableResult testResult = testResult(UsesErrorCollectorCheckSucceedsWithAssumptionViolatedException.class);
    assertThat(testResult, hasSingleFailureMatching(CoreMatchers.<Throwable>instanceOf(AssertionError.class)));
    assertThat(testResult, hasFailureContaining("Callable threw AssumptionViolatedException"));
}
Example 21
Project: junit4-master  File: VerifierRuleTest.java View source code
@Test
public void usedErrorCollectorCheckSucceedsWithAssumptionViolatedExceptionShouldFail() {
    PrintableResult testResult = testResult(UsesErrorCollectorCheckSucceedsWithAssumptionViolatedException.class);
    assertThat(testResult, hasSingleFailureMatching(CoreMatchers.<Throwable>instanceOf(AssertionError.class)));
    assertThat(testResult, hasFailureContaining("Callable threw AssumptionViolatedException"));
}
Example 22
Project: resolver-master  File: SpringTransitivityTestCase.java View source code
@Test
public void testVersionOfAOP() {
    File[] libs = Maven.resolver().loadPomFromFile("target/poms/test-spring.xml").importCompileAndRuntimeDependencies().resolve().withTransitivity().asFile();
    boolean found = false;
    for (File file : libs) {
        if (file.getName().startsWith("spring-aop")) {
            Assert.assertThat(file.getName(), CoreMatchers.containsString("4.2.1.RELEASE"));
            found = true;
            break;
        }
    }
    Assert.assertTrue("The transitive dependency spring-aop should have been found", found);
}
Example 23
Project: spring-framework-issues-master  File: ReproTests.java View source code
@Test
public void repro() {
    System.out.println(System.getProperty("java.version"));
    GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
    ctx.load("classpath:org/springframework/issues/ReproTests-context.xml");
    ctx.refresh();
    Foo foo = ctx.getBean(Foo.class);
    assertThat(foo.getBar(), CoreMatchers.notNullValue());
}
Example 24
Project: zoodirector-master  File: ZooDirectorLogDialogTest.java View source code
@Test
public void testLogMessageIsDisplayed() throws Exception {
    ZooDirectorLogDialog logDialog = new ZooDirectorLogDialog();
    Logger testLogger = LoggerFactory.getLogger(ZooDirectorLogDialogTest.class);
    String testMessage = "test message";
    testLogger.error(testMessage);
    testLogger.info(testMessage);
    Matcher testErrorMessageMatcher = CoreMatchers.containsString("ERROR : " + testMessage);
    Matcher testInfoMessageMatcher = CoreMatchers.containsString("INFO  : " + testMessage);
    Assert.assertThat(logDialog.logTextArea.getText(), testErrorMessageMatcher);
    Assert.assertThat(logDialog.logTextArea.getText(), testInfoMessageMatcher);
    Assert.assertThat(logDialog.lastLogTextField.getText(), testInfoMessageMatcher);
}
Example 25
Project: embedded-db-junit-master  File: EmbeddedDatabaseRulePredefinedNameTest.java View source code
@Test
public void testB() throws Exception {
    try (final Connection connection = embeddedDatabaseRule.getConnection();
        final PreparedStatement selectStatement = connection.prepareStatement("SELECT COUNT(*) FROM A")) {
        final ResultSet result = selectStatement.executeQuery();
        assertThat(result.next(), CoreMatchers.equalTo(true));
        assertThat(result.getInt(1), equalTo(0));
    }
}
Example 26
Project: geotools-master  File: MongoUtilTest.java View source code
@Test
public void set() {
    DBObject dbo = new BasicDBObject();
    Object result;
    MongoUtil.setDBOValue(dbo, "root.child1", 1d);
    result = MongoUtil.getDBOValue(dbo, "root.child1");
    assertThat(result, is(CoreMatchers.instanceOf(Double.class)));
    assertThat((Double) result, is(equalTo(1d)));
    MongoUtil.setDBOValue(dbo, "root.child2", "one");
    result = MongoUtil.getDBOValue(dbo, "root.child2");
    assertThat(result, is(CoreMatchers.instanceOf(String.class)));
    assertThat((String) result, is(equalTo("one")));
    result = MongoUtil.getDBOValue(dbo, "root.doesnotexists");
    assertThat(result, is(nullValue()));
    result = MongoUtil.getDBOValue(dbo, "bugusroot.neglectedchild");
    assertThat(result, is(nullValue()));
}
Example 27
Project: gocd-master  File: RemoveAdminPermissionFilterTest.java View source code
@Test
public void shouldInitializeRemoveAdminPermissionFilterWithSListeners() throws Exception {
    removeAdminPermissionFilter.initialize();
    verify(goConfigService, times(2)).register(configChangedListenerArgumentCaptor.capture());
    List<ConfigChangedListener> registeredListeners = configChangedListenerArgumentCaptor.getAllValues();
    assertThat(registeredListeners.get(0), CoreMatchers.instanceOf(RemoveAdminPermissionFilter.class));
    assertThat(registeredListeners.get(0), is(removeAdminPermissionFilter));
    assertThat(registeredListeners.get(1), CoreMatchers.instanceOf(SecurityConfigChangeListener.class));
}
Example 28
Project: kairosdb-master  File: DatastoreQueryHealthCheckTest.java View source code
@Test
public void testCheckUnHealthy() throws Exception {
    Exception exception = new DatastoreException("Error message");
    when(datastore.getMetricNames()).thenThrow(exception);
    Result result = healthCheck.check();
    assertFalse(result.isHealthy());
    assertThat(result.getError(), CoreMatchers.<Throwable>equalTo(exception));
    assertThat(result.getMessage(), equalTo(exception.getMessage()));
}
Example 29
Project: camel-master  File: QuickfixjSpringTest.java View source code
@Test
public void configureInSpring() throws Exception {
    if (isJava16()) {
        // cannot test on java 1.6
        return;
    }
    SessionID sessionID = new SessionID("FIX.4.2:INITIATOR->ACCEPTOR");
    QuickfixjConfiguration configuration = context.getRegistry().lookupByNameAndType("quickfixjConfiguration", QuickfixjConfiguration.class);
    SessionSettings springSessionSettings = configuration.createSessionSettings();
    Properties sessionProperties = springSessionSettings.getSessionProperties(sessionID, true);
    assertThat(sessionProperties.get("ConnectionType").toString(), CoreMatchers.is("initiator"));
    assertThat(sessionProperties.get("SocketConnectProtocol").toString(), CoreMatchers.is("VM_PIPE"));
    QuickfixjComponent component = context.getComponent("quickfix", QuickfixjComponent.class);
    assertThat(component.isLazyCreateEngines(), is(false));
    QuickfixjEngine engine = component.getEngines().values().iterator().next();
    assertThat(engine.isInitialized(), is(true));
    QuickfixjComponent lazyComponent = context.getComponent("lazyQuickfix", QuickfixjComponent.class);
    assertThat(lazyComponent.isLazyCreateEngines(), is(true));
    QuickfixjEngine lazyEngine = lazyComponent.getEngines().values().iterator().next();
    assertThat(lazyEngine.isInitialized(), is(false));
    assertThat(engine.getMessageFactory(), is(instanceOf(CustomMessageFactory.class)));
}
Example 30
Project: fixture-factory-master  File: FixtureImmutableTest.java View source code
@Test
public void shouldWorkWhenChainingPropertiesUsingRelations() {
    RoutePlanner routePlanner = Fixture.from(RoutePlanner.class).gimme("chainedRoutePlanner");
    assertThat(routePlanner.getRoute().getId().getValue(), CoreMatchers.<Long>either(equalTo(3L)).or(equalTo(4L)));
    assertThat(routePlanner.getRoute().getId().getSeq(), CoreMatchers.<Long>either(equalTo(300L)).or(equalTo(400L)));
    assertNotNull(routePlanner.getRoute().getCities().get(0).getName());
}
Example 31
Project: pentaho-reporting-master  File: FormulaHeaderReadHandlerTest.java View source code
@Test
public void testStartParsing() throws SAXException {
    XMLAttributesImpl attrs = new XMLAttributesImpl();
    attrs.addAttribute(new QName(null, "name", null, URI), ATTR_TYPE, NAME_VALUE);
    attrs.addAttribute(new QName(null, "formula", null, URI), ATTR_TYPE, FORMULA_VALUE);
    AttributesProxy fAttributesProxy = new AttributesProxy(attrs);
    handler.startParsing(fAttributesProxy);
    Object result = handler.getObject();
    assertThat(result, is(notNullValue()));
    assertThat(result, is(CoreMatchers.instanceOf(FormulaHeader.class)));
    FormulaHeader formulaHeader = (FormulaHeader) result;
    assertThat(formulaHeader.getName(), is(equalTo(NAME_VALUE)));
}
Example 32
Project: RobolectricSample-master  File: ApiGatewayTest.java View source code
@Test
public void shouldMakeRemoteCalls() {
    Robolectric.getBackgroundScheduler().pause();
    ApiRequest apiRequest = new TestApiRequest();
    apiGateway.makeRequest(apiRequest, responseCallbacks);
    Robolectric.addPendingHttpResponse(200, "response body");
    Robolectric.getBackgroundScheduler().runOneTask();
    HttpRequestInfo sentHttpRequestData = Robolectric.getSentHttpRequestInfo(0);
    HttpRequest sentHttpRequest = sentHttpRequestData.getHttpRequest();
    assertThat(sentHttpRequest.getRequestLine().getUri(), equalTo("www.example.com"));
    assertThat(sentHttpRequest.getRequestLine().getMethod(), equalTo(HttpGet.METHOD_NAME));
    assertThat(sentHttpRequest.getHeaders("foo")[0].getValue(), equalTo("bar"));
    CredentialsProvider credentialsProvider = (CredentialsProvider) sentHttpRequestData.getHttpContext().getAttribute(ClientContext.CREDS_PROVIDER);
    assertThat(credentialsProvider.getCredentials(AuthScope.ANY).getUserPrincipal().getName(), CoreMatchers.equalTo("spongebob"));
    assertThat(credentialsProvider.getCredentials(AuthScope.ANY).getPassword(), CoreMatchers.equalTo("squarepants"));
}
Example 33
Project: SOS-master  File: SensorMLDecoderV20Test.java View source code
@Test
@Ignore("Activate again and continue implementation here")
public void shouldDecodeDataInterfaceInterfaceParameters() throws OwsExceptionReport {
    DataInterfaceType xbDataInterface = DataInterfaceType.Factory.newInstance();
    DataRecordPropertyType xbInterfaceParameters = xbDataInterface.addNewInterfaceParameters();
    Field field = xbInterfaceParameters.addNewDataRecord().addNewField();
    field.setName("test-field-name");
    SmlDataInterface parsedDataInterface = new SensorMLDecoderV20().parseDataInterfaceType(xbDataInterface);
    assertThat(parsedDataInterface.isSetInterfaceParameters(), is(true));
    assertThat(parsedDataInterface.getInterfaceParameters(), CoreMatchers.isA(SweDataRecord.class));
}
Example 34
Project: wicket-master  File: WebSocketBehaviorTestPage.java View source code
@Override
protected void onPush(WebSocketRequestHandler handler, IWebSocketPushMessage message) {
    Assert.assertThat(message, CoreMatchers.instanceOf(WebSocketTesterBehaviorTest.BroadcastMessage.class));
    WebSocketTesterBehaviorTest.BroadcastMessage broadcastMessage = (WebSocketTesterBehaviorTest.BroadcastMessage) message;
    Assert.assertSame(expectedMessage, broadcastMessage);
    String pushedMessage = broadcastMessage.getText().toUpperCase();
    handler.push(pushedMessage);
}
Example 35
Project: cloudify-master  File: ValueDeserializerTest.java View source code
@Test
public void testDeserializeBase64() throws PrivateEc2ParserException {
    SimpleValue mapJson = ParserUtils.mapJson(SimpleValue.class, "{\"Value\": { \"Fn::Base64\" : \"hello world\" }}");
    assertNotNull(mapJson.getValueType());
    String helloWorldBase64 = StringUtils.newStringUtf8(Base64.encodeBase64("hello world".getBytes()));
    Assert.assertThat(mapJson.getValueType().getValue(), CoreMatchers.is("hello world"));
    Assert.assertThat(((Base64Function) mapJson.getValueType()).getEncodedValue(), CoreMatchers.is(helloWorldBase64));
}
Example 36
Project: ehcache3-master  File: EhcacheBasicRemoveTest.java View source code
/**
   * Gets an initialized {@link Ehcache Ehcache} instance
   *
   * @return a new {@code Ehcache} instance
   */
private Ehcache<String, String> getEhcache() {
    final Ehcache<String, String> ehcache = new Ehcache<String, String>(CACHE_CONFIGURATION, this.store, cacheEventDispatcher, LoggerFactory.getLogger(Ehcache.class + "-" + "EhcacheBasicRemoveTest"));
    ehcache.init();
    assertThat("cache not initialized", ehcache.getStatus(), CoreMatchers.is(Status.AVAILABLE));
    this.spiedResilienceStrategy = this.setResilienceStrategySpy(ehcache);
    return ehcache;
}
Example 37
Project: lombok-intellij-plugin-master  File: LoggerCompletionTest.java View source code
private void doTest(String... expectedSuggestions) {
    final String fileName = getTestName(false).replace('$', '/') + ".java";
    myFixture.copyFileToProject(getBasePath() + "/lombok.config", "lombok.config");
    myFixture.configureByFile(getBasePath() + "/" + fileName);
    myFixture.complete(CompletionType.BASIC, 1);
    List<String> autoSuggestions = myFixture.getLookupElementStrings();
    assertNotNull(autoSuggestions);
    assertThat("Autocomplete doesn't contain right suggestions", autoSuggestions, CoreMatchers.hasItems(expectedSuggestions));
}
Example 38
Project: nosql-unit-master  File: CubbyholeTest.java View source code
@Test
@UsingDataSet(locations = "cubbyhole-setup.yml", loadStrategy = LoadStrategyEnum.INSERT)
public void should_get_username_password_in_secured_way() {
    VaultConfig vaultConfig = new VaultConfig();
    vaultConfig.address("http://192.168.99.100:8200");
    Cubbyhole cubbyhole = new Cubbyhole(vaultConfig, "temp");
    final Map<String, String> usernameAndPassword = cubbyhole.getUsernameAndPassword(tempToken);
    assertThat(usernameAndPassword.get("username"), CoreMatchers.is("ada"));
    assertThat(usernameAndPassword.get("password"), CoreMatchers.is("alexandra"));
}
Example 39
Project: ObjectLayout-master  File: SimpleLineTest.java View source code
@Test
public void shouldConstructLine() throws NoSuchMethodException {
    SimpleLine line = new SimpleLine();
    Point endPoint1 = line.getEndPoint1();
    Point endPoint2 = line.getEndPoint2();
    Assert.assertThat(valueOf(endPoint1.getX()), CoreMatchers.is(0L));
    Assert.assertThat(valueOf(endPoint1.getY()), CoreMatchers.is(0L));
    Assert.assertThat(valueOf(endPoint2.getX()), CoreMatchers.is(0L));
    Assert.assertThat(valueOf(endPoint2.getY()), CoreMatchers.is(0L));
    Line line2 = new Line(1, 2, 3, 4);
    endPoint1 = line2.getEndPoint1();
    endPoint2 = line2.getEndPoint2();
    Assert.assertThat(valueOf(endPoint1.getX()), CoreMatchers.is(1L));
    Assert.assertThat(valueOf(endPoint1.getY()), CoreMatchers.is(2L));
    Assert.assertThat(valueOf(endPoint2.getX()), CoreMatchers.is(3L));
    Assert.assertThat(valueOf(endPoint2.getY()), CoreMatchers.is(4L));
    Line line3 = new Line(line2);
    endPoint1 = line3.getEndPoint1();
    endPoint2 = line3.getEndPoint2();
    Assert.assertThat(valueOf(endPoint1.getX()), CoreMatchers.is(1L));
    Assert.assertThat(valueOf(endPoint1.getY()), CoreMatchers.is(2L));
    Assert.assertThat(valueOf(endPoint2.getX()), CoreMatchers.is(3L));
    Assert.assertThat(valueOf(endPoint2.getY()), CoreMatchers.is(4L));
}
Example 40
Project: OpERP-master  File: ManufacturerServiceTest.java View source code
@Test
public void testSave() {
    Manufacturer savedManufacturer = repo.save(manufacturer);
    Assert.assertThat("Saved and returned object must be same", manufacturer, CoreMatchers.is(savedManufacturer));
    Assert.assertThat("Found and saved must be same", manufacturer, CoreMatchers.is(repo.findOne(savedManufacturer.getManufacturerId())));
}
Example 41
Project: play-geolocation-module.edulify.com-master  File: GeolocationCacheTest.java View source code
@Test
public void shouldAddGeolocationToCacheWhenCacheIsOn() {
    Application application = getApplication(true);
    Helpers.running(application, () -> {
        Geolocation geolocation = new Geolocation(ipAddress, countryCode);
        GeolocationCache cache = application.injector().instanceOf(GeolocationCache.class);
        cache.set(geolocation);
        Assert.assertThat(cache.get(ipAddress), CoreMatchers.notNullValue());
    });
}
Example 42
Project: test-streamer-master  File: ExcelTest.java View source code
@Test
public void japanCode() throws IOException {
    System.out.println(getClass().getClassLoader());
    InputStream in = getClass().getResourceAsStream("/iso_3166_2_countries.xlsx");
    assertNotNull(in);
    try {
        XSSFWorkbook book = new XSSFWorkbook(in);
        XSSFSheet sheet = book.getSheetAt(0);
        for (int i = sheet.getFirstRowNum(); i < sheet.getLastRowNum(); i++) {
            XSSFRow row = sheet.getRow(i);
            if ("Japan".equalsIgnoreCase(row.getCell(1).getStringCellValue())) {
                assertThat("Japanese currency is JPY.", row.getCell(7).getStringCellValue(), CoreMatchers.is("JPY"));
            }
        }
    } finally {
        IOUtils.closeQuietly(in);
    }
}
Example 43
Project: DeviceConnect-Android-master  File: NormalServiceDiscoveryProfileTestCase.java View source code
/**
     * サービス�探索を行�.
     * 
     * <pre>
     * �Intent通信】
     * Method: GET
     * Extra:
     *     profile=serviceDiscovery
     * </pre>
     * 
     * <pre>
     * �期待�る動作】
     * ・resultã?«0ã?Œè¿”ã?£ã?¦ã??ã‚‹ã?“ã?¨ã€‚
     * ・servicesã?«å°‘ã?ªã??ã?¨ã‚‚1ã?¤ä»¥ä¸Šã?®ã‚µãƒ¼ãƒ“スã?Œç™ºè¦‹ã?•ã‚Œã‚‹ã?“ã?¨ã€‚
     * ・services�中�「Test Success Device��nameを���サービス�存在�る��。
     * </pre>
     */
@Test
public void testGetServices() {
    String uri = "http://localhost:4035/gotapi/serviceDiscovery";
    uri += "?accessToken=" + getAccessToken();
    DConnectResponseMessage response = mDConnectSDK.get(uri);
    assertThat(response, is(notNullValue()));
    assertThat(response.getResult(), is(DConnectMessage.RESULT_OK));
    List<Object> services = response.getList("services");
    assertThat(services, is(CoreMatchers.notNullValue()));
    assertThat(services.size(), is(greaterThan(0)));
    for (Object obj : services) {
        DConnectMessage service = (DConnectMessage) obj;
        String id = service.getString("id");
        String name = service.getString("name");
        assertThat(id, is(CoreMatchers.notNullValue()));
        assertThat(name, is(CoreMatchers.notNullValue()));
    }
}
Example 44
Project: error-prone-master  File: ExpectedExceptionCheckerTest.java View source code
@Test
public void expect() throws IOException {
    BugCheckerRefactoringTestHelper.newInstance(new ExpectedExceptionChecker(), getClass()).addInputLines("in/ExceptionTest.java", "import static com.google.common.truth.Truth.assertThat;", "import java.io.IOException;", "import java.nio.file.*;", "import org.junit.Test;", "import org.junit.Rule;", "import org.hamcrest.CoreMatchers;", "import org.junit.rules.ExpectedException;", "class ExceptionTest {", "  @Rule ExpectedException thrown = ExpectedException.none();", "  @Test", "  public void test() throws Exception {", "    if (true) {", "      Path p = Paths.get(\"NOSUCH\");", "      thrown.expect(IOException.class);", "      thrown.expect(CoreMatchers.is(CoreMatchers.instanceOf(IOException.class)));", "      thrown.expectCause(", "          CoreMatchers.is(CoreMatchers.instanceOf(IOException.class)));", "      thrown.expectMessage(\"error\");", "      thrown.expectMessage(CoreMatchers.containsString(\"error\"));", "      Files.readAllBytes(p);", "      assertThat(Files.exists(p)).isFalse();", "    }", "  }", "}").addOutputLines("out/ExceptionTest.java", "import static com.google.common.truth.Truth.assertThat;", "import static org.hamcrest.MatcherAssert.assertThat;", "import static org.junit.Assert.expectThrows;", "", "import java.io.IOException;", "import java.nio.file.*;", "import org.hamcrest.CoreMatchers;", "import org.junit.Rule;", "import org.junit.Test;", "import org.junit.rules.ExpectedException;", "class ExceptionTest {", "  @Rule ExpectedException thrown = ExpectedException.none();", "  @Test", "  public void test() throws Exception {", "    if (true) {", "      Path p = Paths.get(\"NOSUCH\");", "      IOException thrown =", "          expectThrows(IOException.class, () -> Files.readAllBytes(p));", "      assertThat(thrown,", "          CoreMatchers.is(CoreMatchers.instanceOf(IOException.class)));", "      assertThat(thrown.getCause(),", "          CoreMatchers.is(CoreMatchers.instanceOf(IOException.class)));", "      assertThat(thrown).hasMessageThat().contains(\"error\");", "      assertThat(thrown.getMessage(), CoreMatchers.containsString(\"error\"));", "      assertThat(Files.exists(p)).isFalse();", "    }", "  }", "}").allowBreakingChanges().doTest();
}
Example 45
Project: FitGoodies-master  File: SetupFixtureTest.java View source code
@Test
public void testHelperInteraction() throws Exception {
    useTable(tr("serverHost", "server-host"), tr("serverPort", "4444"), tr("browserStartCommand", "browser-Start-Command"), tr("browserURL", "browser-URL"), tr("speed", "400"), tr("timeout", "3000"), tr("retryTimeout", "$timeout"), tr("retryInterval", "10"), tr("takeScreenshots", "$screenshot"), tr("sleepBeforeScreenshot", "500"), tr("start", "start config"));
    preparePreprocessWithConversion(String.class, "server-host", "server-host");
    preparePreprocessWithConversion(String.class, "4444", "4444");
    preparePreprocessWithConversion(String.class, "browser-Start-Command", "browser-Start-Command");
    preparePreprocessWithConversion(String.class, "browser-URL", "browser-URL");
    preparePreprocessWithConversion(String.class, "400", "400");
    preparePreprocessWithConversion(String.class, "3000", "3000");
    preparePreprocessWithConversion(String.class, "$timeout", "40");
    preparePreprocessWithConversion(String.class, "10", "10");
    preparePreprocessWithConversion(String.class, "$screenshot", "true");
    preparePreprocessWithConversion(String.class, "500", "500");
    preparePreprocessWithConversion(String.class, "start config", "start config");
    helper.setCommandProcessor(commandProcessor);
    run();
    assertCounts(0, 0, 0, 0);
    assertThat(helper.getServerHost(), is(equalTo("server-host")));
    assertThat(helper.getServerPort(), is(equalTo((Object) 4444)));
    assertThat(helper.getBrowserStartCommand(), is(equalTo("browser-Start-Command")));
    assertThat(helper.getBrowserURL(), is(equalTo("browser-URL")));
    assertThat(helper.getSpeed(), is(equalTo(400)));
    assertThat(helper.getTimeout(), is(equalTo((Object) 3000L)));
    assertThat(helper.getRetryTimeout(), is(equalTo((Object) 40L)));
    assertThat(helper.getRetryInterval(), is(equalTo((Object) 10L)));
    assertThat(helper.getTakeScreenshots(), is(true));
    assertThat(helper.sleepBeforeScreenshot(), is(equalTo((Object) 500L)));
    assertThat(helper.getCommandProcessor(), not(CoreMatchers.is(nullValue())));
    verify(commandProcessor).start("start config");
    verify(commandProcessor).doCommand("setTimeout", new String[] { "3000" });
}
Example 46
Project: kairosdb-client-master  File: GroupByDeserializerTest.java View source code
@Test
public void test_unknown_grouper() {
    CustomGroupResult result = (CustomGroupResult) gson.fromJson("{'name': 'bogus', 'value': 5}", GroupResult.class);
    assertThat(result, instanceOf(CustomGroupResult.class));
    assertThat(result.getName(), equalTo("bogus"));
    assertThat(result.getProperties().get("value"), CoreMatchers.<Object>equalTo(5.0));
}
Example 47
Project: newts-master  File: SamplesResourceTest.java View source code
@Test
public void testGetSamples() {
    final Results<Sample> results = new Results<>();
    when(m_repository.select(eq(Context.DEFAULT_CONTEXT), eq(new Resource("localhost")), eq(Optional.of(Timestamp.fromEpochSeconds(900000000))), eq(Optional.of(Timestamp.fromEpochSeconds(900003600))))).thenReturn(results);
    assertThat(m_resource.getSamples(new Resource("localhost"), Optional.of(new TimestampParam("1998-07-09T11:00:00-0500")), Optional.of(new TimestampParam("1998-07-09T12:00:00-0500")), Optional.<String>absent()), CoreMatchers.instanceOf(Collection.class));
}
Example 48
Project: spring-xd-master  File: DefaultSimpleModuleInformationResolverTests.java View source code
@Test
public void doesNotSupportComposedModules() {
    DefaultSimpleModuleInformationResolver resolver = new DefaultSimpleModuleInformationResolver();
    ModuleDefinition filter = ModuleDefinitions.simple("filter", ModuleType.processor, "classpath:dontcare");
    ModuleDefinition transform = ModuleDefinitions.simple("transform", ModuleType.processor, "classpath:dontcare");
    ModuleInformation result = resolver.resolve(ModuleDefinitions.composed("foo", ModuleType.processor, "filter | transform", Arrays.asList(filter, transform)));
    assertThat(result, CoreMatchers.nullValue());
}
Example 49
Project: RoboBuggy-master  File: ExpectedExceptionTest.java View source code
@Parameters(name = "{0}")
public static Collection<Object[]> testsWithEventMatcher() {
    return asList(new Object[][] { { EmptyTestExpectingNoException.class, everyTestRunSuccessful() }, { ThrowExceptionWithExpectedType.class, everyTestRunSuccessful() }, { ThrowExceptionWithExpectedPartOfMessage.class, everyTestRunSuccessful() }, { ThrowExceptionWithWrongType.class, hasSingleFailureWithMessage(startsWith("\nExpected: an instance of java.lang.NullPointerException")) }, { HasWrongMessage.class, hasSingleFailureWithMessage(startsWith("\nExpected: exception with message a string containing \"expectedMessage\"\n" + "     but: message was \"actualMessage\"")) }, { ThrowNoExceptionButExpectExceptionWithType.class, hasSingleFailureWithMessage("Expected test to throw an instance of java.lang.NullPointerException") }, { WronglyExpectsExceptionMessage.class, hasSingleFailure() }, { ExpectsSubstring.class, everyTestRunSuccessful() }, { ExpectsSubstringNullMessage.class, hasSingleFailureWithMessage(startsWith("\nExpected: exception with message a string containing \"anything!\"")) }, { ExpectsMessageMatcher.class, everyTestRunSuccessful() }, { ExpectedMessageMatcherFails.class, hasSingleFailureWithMessage(startsWith("\nExpected: exception with message \"Wrong start\"")) }, { ExpectsMatcher.class, everyTestRunSuccessful() }, { ExpectAssertionErrorWhichIsNotThrown.class, hasSingleFailure() }, { FailedAssumptionAndExpectException.class, hasSingleAssumptionFailure() }, { FailBeforeExpectingException.class, hasSingleFailureWithMessage(ARBITRARY_MESSAGE) }, { ExpectsMultipleMatchers.class, hasSingleFailureWithMessage(startsWith("\nExpected: (an instance of java.lang.IllegalArgumentException and exception with message a string containing \"Ack!\")")) }, { ThrowExceptionWithMatchingCause.class, everyTestRunSuccessful() }, { ThrowExpectedNullCause.class, everyTestRunSuccessful() }, { ThrowUnexpectedCause.class, hasSingleFailureWithMessage(CoreMatchers.<String>allOf(startsWith("\nExpected: ("), containsString("exception with cause is <java.lang.NullPointerException: expected cause>"), containsString("cause was <java.lang.NullPointerException: an unexpected cause>"), containsString("Stacktrace was: java.lang.IllegalArgumentException: Ack!"), containsString("Caused by: java.lang.NullPointerException: an unexpected cause"))) }, { UseNoCustomMessage.class, hasSingleFailureWithMessage("Expected test to throw an instance of java.lang.IllegalArgumentException") }, { UseCustomMessageWithoutPlaceHolder.class, hasSingleFailureWithMessage(ARBITRARY_MESSAGE) }, { UseCustomMessageWithPlaceHolder.class, hasSingleFailureWithMessage(ARBITRARY_MESSAGE + " - an instance of java.lang.IllegalArgumentException") } });
}
Example 50
Project: sosies-generator-master  File: ExpectedExceptionTest.java View source code
@Parameters(name = "{0}")
public static Collection<Object[]> testsWithEventMatcher() {
    return asList(new Object[][] { { EmptyTestExpectingNoException.class, everyTestRunSuccessful() }, { ThrowExceptionWithExpectedType.class, everyTestRunSuccessful() }, { ThrowExceptionWithExpectedPartOfMessage.class, everyTestRunSuccessful() }, { ThrowExceptionWithWrongType.class, hasSingleFailureWithMessage(startsWith("\nExpected: an instance of java.lang.NullPointerException")) }, { HasWrongMessage.class, hasSingleFailureWithMessage(startsWith("\nExpected: exception with message a string containing \"expectedMessage\"\n" + "     but: message was \"actualMessage\"")) }, { ThrowNoExceptionButExpectExceptionWithType.class, hasSingleFailureWithMessage("Expected test to throw an instance of java.lang.NullPointerException") }, { WronglyExpectsExceptionMessage.class, hasSingleFailure() }, { ExpectsSubstring.class, everyTestRunSuccessful() }, { ExpectsSubstringNullMessage.class, hasSingleFailureWithMessage(startsWith("\nExpected: exception with message a string containing \"anything!\"")) }, { ExpectsMessageMatcher.class, everyTestRunSuccessful() }, { ExpectedMessageMatcherFails.class, hasSingleFailureWithMessage(startsWith("\nExpected: exception with message \"Wrong start\"")) }, { ExpectsMatcher.class, everyTestRunSuccessful() }, { ExpectAssertionErrorWhichIsNotThrown.class, hasSingleFailure() }, { FailedAssumptionAndExpectException.class, hasSingleAssumptionFailure() }, { FailBeforeExpectingException.class, hasSingleFailureWithMessage(ARBITRARY_MESSAGE) }, { ExpectsMultipleMatchers.class, hasSingleFailureWithMessage(startsWith("\nExpected: (an instance of java.lang.IllegalArgumentException and exception with message a string containing \"Ack!\")")) }, { ThrowExceptionWithMatchingCause.class, everyTestRunSuccessful() }, { ThrowExpectedNullCause.class, everyTestRunSuccessful() }, { ThrowUnexpectedCause.class, hasSingleFailureWithMessage(CoreMatchers.<String>allOf(startsWith("\nExpected: ("), containsString("exception with cause is <java.lang.NullPointerException: expected cause>"), containsString("cause was <java.lang.NullPointerException: an unexpected cause>"), containsString("Stacktrace was: java.lang.IllegalArgumentException: Ack!"), containsString("Caused by: java.lang.NullPointerException: an unexpected cause"))) }, { UseNoCustomMessage.class, hasSingleFailureWithMessage("Expected test to throw an instance of java.lang.IllegalArgumentException") }, { UseCustomMessageWithoutPlaceHolder.class, hasSingleFailureWithMessage(ARBITRARY_MESSAGE) }, { UseCustomMessageWithPlaceHolder.class, hasSingleFailureWithMessage(ARBITRARY_MESSAGE + " - an instance of java.lang.IllegalArgumentException") } });
}
Example 51
Project: jmeter-master  File: XPathUtilTest.java View source code
@Test()
public void testFormatXmlInvalid() {
    PrintStream origErr = System.err;
    // The parser will print an error, so let it go somewhere, where we will
    // not see it
    System.setErr(null);
    assertThat("No well formed xml here", CoreMatchers.is(XPathUtil.formatXml("No well formed xml here")));
    System.setErr(origErr);
}
Example 52
Project: c10n-master  File: C10NMessageTest.java View source code
@Test
public void asMapContainsAllMappingAsAMap() throws Exception {
    MyMsg myMsg = C10N.get(MyMsg.class);
    assertThat(myMsg.myMsg().asMap(), CoreMatchers.<Map<Locale, String>>is(ImmutableMap.of(C10N.FALLBACK_LOCALE, "fallback", Locale.ENGLISH, "english", Locale.JAPANESE, "japanese")));
    assertThat(myMsg.myMsgWithArg(234).asMap(), CoreMatchers.<Map<Locale, String>>is(ImmutableMap.of(C10N.FALLBACK_LOCALE, "fallback 234", Locale.ENGLISH, "english 234", Locale.JAPANESE, "japanese 234")));
}
Example 53
Project: FlockDB-Client-master  File: FlockDBTest.java View source code
@Test
public void returnsBuilderWithReferenceToBackingClientAndSelectionQueryOnSelect() throws IOException, FlockException {
    SelectionQuery firstQuery = simpleSelection(1, 2, OUTGOING);
    SelectionBuilder builder = new FlockDB(backingFlockMock).select(firstQuery);
    assertThat(builder.getBackingFlockClient(), is(sameInstance(backingFlockMock)));
    assertThat(builder.getQueries(), contains(aSelectQuery(withOperations(CoreMatchers.<Iterable<? extends SelectOperation>>is(firstQuery.getSelectOperations())), withCursor(-1))));
}
Example 54
Project: floodlight-master  File: OFSwitchHandshakeHandlerVer10Test.java View source code
@Override
@Test
public void moveToWaitSwitchDriverSubHandshake() throws Exception {
    moveToWaitDescriptionStatReply();
    handleDescStatsAndCreateSwitch(false);
    assertThat(switchHandler.getStateForTesting(), CoreMatchers.instanceOf(OFSwitchHandshakeHandler.WaitSwitchDriverSubHandshakeState.class));
    assertThat("Unexpected message captured", connection.getMessages(), Matchers.empty());
    verify(sw);
}
Example 55
Project: Jnario-master  File: AnnotationsSpec.java View source code
@Test
@Named("should support class annotations for \\\'describe\\\'")
@Order(1)
public void _shouldSupportClassAnnotationsForDescribe() throws Exception {
    final String spec = "\r\n\t\t\tpackage bootstrap\r\n\t\t\timport static org.hamcrest.CoreMatchers.*\t\t\t\r\n\t\t\timport com.google.inject.Singleton\r\n\r\n\t\t\t@Singleton\t\t\t\r\n\t\t\tdescribe \"Annotations\" {\r\n\t\t\t\r\n\t\t\tfact \"should support class annotations for describe\"{\r\n\t\t\t\t\tval annotation = typeof(AnnotationsSpec).getAnnotation(typeof(Singleton))\r\n\t\t\t\t\tannotation should not be null\r\n\t\t\t\t} \r\n\t\t\t\t\t\t\r\n\t\t\t}\r\n\t\t";
    this._behaviorExecutor.executesSuccessfully(spec);
}
Example 56
Project: org.ops4j.pax.url-master  File: MetaTypeTest.java View source code
@Test
public void checkMetadata() throws IOException, BundleException {
    Bundle bundle = BundleUtils.getBundle(bc, "org.ops4j.pax.url.mvn");
    assertThat(bundle, is(notNullValue()));
    MetaTypeInformation metaTypeInformation = metaTypeService.getMetaTypeInformation(bundle);
    assertThat(metaTypeInformation, is(notNullValue()));
    String[] pids = metaTypeInformation.getPids();
    assertThat(pids, is(notNullValue()));
    assertThat(pids.length, is(1));
    assertThat(pids[0], is("org.ops4j.pax.url.mvn"));
    ObjectClassDefinition ocd = metaTypeInformation.getObjectClassDefinition(pids[0], null);
    assertThat(ocd, is(notNullValue()));
    assertThat(ocd.getID(), is("org.ops4j.pax.url.mvn"));
    AttributeDefinition[] attrDefs = ocd.getAttributeDefinitions(ObjectClassDefinition.ALL);
    assertThat(attrDefs, is(notNullValue()));
    assertThat(attrDefs.length, is(10));
    List<String> ids = new ArrayList<String>();
    for (AttributeDefinition attrDef : attrDefs) {
        String id = attrDef.getID().replace("org.ops4j.pax.url.mvn.", "");
        ids.add(id);
    }
    assertThat(ids, CoreMatchers.hasItems("certificateCheck", "defaultRepositories", "globalUpdatePolicy", "localRepository", "proxies", "proxySupport", "repositories", "security", "settings", "timeout"));
}
Example 57
Project: shard-master  File: ShardingForNullableWithAggregateTest.java View source code
@Test
public void assertSelectCount() throws SQLException, DatabaseUnitException {
    String sql = "SELECT COUNT(`user_id`) FROM `t_order`";
    try (Connection conn = shardingDataSource.getConnection();
        PreparedStatement ps = conn.prepareStatement(sql);
        ResultSet rs = ps.executeQuery()) {
        assertThat(rs.next(), is(true));
        assertThat(rs.getInt("COUNT(`user_id`)"), is(0));
        assertThat(rs.getInt(1), is(0));
        assertThat(rs.getObject("COUNT(`user_id`)"), CoreMatchers.<Object>is(new BigDecimal("0")));
        assertThat(rs.getObject(1), CoreMatchers.<Object>is(new BigDecimal("0")));
        assertThat(rs.next(), is(false));
    }
}
Example 58
Project: sharding-jdbc-master  File: ShardingForNullableWithAggregateTest.java View source code
@Test
public void assertSelectCount() throws SQLException, DatabaseUnitException {
    String sql = "SELECT COUNT(`user_id`) FROM `t_order`";
    try (Connection conn = shardingDataSource.getConnection();
        PreparedStatement ps = conn.prepareStatement(sql);
        ResultSet rs = ps.executeQuery()) {
        assertThat(rs.next(), is(true));
        assertThat(rs.getInt("COUNT(`user_id`)"), is(0));
        assertThat(rs.getInt(1), is(0));
        assertThat(rs.getObject("COUNT(`user_id`)"), CoreMatchers.<Object>is(new BigDecimal("0")));
        assertThat(rs.getObject(1), CoreMatchers.<Object>is(new BigDecimal("0")));
        assertThat(rs.next(), is(false));
    }
}
Example 59
Project: transaction-master  File: ShardingForNullableWithAggregateTest.java View source code
@Test
public void assertSelectCount() throws SQLException, DatabaseUnitException {
    String sql = "SELECT COUNT(`user_id`) FROM `t_order`";
    try (Connection conn = shardingDataSource.getConnection();
        PreparedStatement ps = conn.prepareStatement(sql);
        ResultSet rs = ps.executeQuery()) {
        assertThat(rs.next(), is(true));
        assertThat(rs.getInt("COUNT(`user_id`)"), is(0));
        assertThat(rs.getInt(1), is(0));
        assertThat(rs.getObject("COUNT(`user_id`)"), CoreMatchers.<Object>is(new BigDecimal("0")));
        assertThat(rs.getObject(1), CoreMatchers.<Object>is(new BigDecimal("0")));
        assertThat(rs.next(), is(false));
    }
}
Example 60
Project: checkstyle-master  File: InputParenPad.java View source code
private void except() {
    // warning
    java.util.ArrayList<Integer> arrlist = new java.util.ArrayList<Integer>(5);
    // warning
    arrlist.add(20);
    // warning
    arrlist.add(15);
    // warning
    arrlist.add(30);
    arrlist.add(45);
    try {
        // warning
        (arrlist).remove(2);
    } catch (// warning
    IndexOutOfBoundsException // warning
    x) {
        x.getMessage();
    }
    // warning
    org.junit.Assert.assertThat("123", org.hamcrest.CoreMatchers.is("123"));
    // warning
    org.junit.Assert.assertThat(// warning
    "Help! Integers don't work", 0, // warning
    org.hamcrest.CoreMatchers.is(1));
}
Example 61
Project: ddf-master  File: TestAttributeFileClaimsHandler.java View source code
@Test
public void testRetrieveClaimsValuesNullPrincipal() {
    ClaimsParameters claimsParameters = new ClaimsParameters();
    ClaimCollection claimCollection = new ClaimCollection();
    ProcessedClaimCollection processedClaims = attributeFileClaimsHandler.retrieveClaimValues(claimCollection, claimsParameters);
    Assert.assertThat(processedClaims.size(), CoreMatchers.is(equalTo(0)));
}
Example 62
Project: gelfj-master  File: GelfHandlerTest.java View source code
@Test
public void testSetAdditionalField() {
    GelfHandler gelfHandler = new GelfHandler();
    gelfHandler.setAdditionalField(null);
    gelfHandler.setAdditionalField("=");
    gelfHandler.setAdditionalField("==");
    Map<String, String> fields = gelfHandler.getFields();
    assertThat("No empty key exists", fields.get(""), CoreMatchers.nullValue());
}
Example 63
Project: jslint4java-master  File: ReportWriterImplTest.java View source code
/**
     * issue 65: If we configure an invalid report xml, we should blow up with a
     * {@link RuntimeException} (wrapping a
     * {@link IOException}). Instead, we're blowing up with an
     * {@link NullPointerException}when we try to close().
     */
@Test
public void closeDoesntHideIoExceptionWithNullPointerException() throws IOException {
    kaboom.expect(RuntimeException.class);
    kaboom.expectCause(CoreMatchers.<Throwable>instanceOf(IOException.class));
    // This is guaranteed to fail as it's a file not a directory.
    File f = tmpf.newFile("bob");
    ReportWriter rw = new ReportWriterImpl(new File(f, REPORT_XML), formatter);
    try {
        rw.open();
    } finally {
        // This shouldn't blow up with an NPE.
        rw.close();
    }
}
Example 64
Project: MutabilityDetector-master  File: MutabilityCheckerTest.java View source code
@Test
public void onlyOneReasonIsRaisedForAssigningAbstractTypeToField() throws Exception {
    AnalysisResult analysisResult = getAnalysisResult(MutableByAssigningAbstractTypeToField.class);
    Collection<MutableReasonDetail> reasons = analysisResult.reasons;
    assertThat(formatReasons(reasons), reasons.size(), is(1));
    Reason reason = reasons.iterator().next().reason();
    assertThat(reason, CoreMatchers.<Reason>is(ABSTRACT_TYPE_TO_FIELD));
}
Example 65
Project: neo4j-enterprise-master  File: MultiPaxosTest.java View source code
@Test
public void testDecision() throws ExecutionException, InterruptedException, URISyntaxException {
    Map<String, String> map1 = new AtomicBroadcastMap<String, String>(cluster.getNodes().get(0).newClient(AtomicBroadcast.class), cluster.getNodes().get(0).newClient(Snapshot.class));
    Map<String, String> map2 = new AtomicBroadcastMap<String, String>(cluster.getNodes().get(1).newClient(AtomicBroadcast.class), cluster.getNodes().get(1).newClient(Snapshot.class));
    map1.put("foo", "bar");
    network.tick(30);
    Object foo = map1.get("foo");
    Assert.assertThat(foo.toString(), equalTo("bar"));
    map1.put("bar", "foo");
    network.tick(30);
    Object bar = map2.get("bar");
    Assert.assertThat(bar.toString(), equalTo("foo"));
    map1.put("foo", "bar2");
    network.tick(30);
    foo = map2.get("foo");
    Assert.assertThat(foo.toString(), equalTo("bar2"));
    map1.clear();
    network.tick(30);
    foo = map2.get("foo");
    Assert.assertThat(foo, CoreMatchers.nullValue());
}
Example 66
Project: octarine-master  File: RecordJoinerTest.java View source code
@Test
public void three_way_join() {
    List<Record> joined = RecordJoins.join(RecordJoins.join(books).on(authorId).to(id).manyToOne(authors)).on(publisherId).to(id).manyToOne(publishers).map( r -> r.select(publisherName, authorName, bookName)).filter(authorName.is("Alan Goodyear")).collect(Collectors.toList());
    assertThat(joined, CoreMatchers.hasItems($$(bookName.of("Amorous Encounters"), authorName.of("Alan Goodyear"), publisherName.of("Bills And Moon")), $$(bookName.of("The Cromulence Of Truths"), authorName.of("Alan Goodyear"), publisherName.of("Servo"))));
}
Example 67
Project: pgjdbc-master  File: ReplicationConnectionTest.java View source code
@Test
public void testReplicationCommandResultSetAccessByIndex() throws Exception {
    Statement statement = replConnection.createStatement();
    ResultSet resultSet = statement.executeQuery("IDENTIFY_SYSTEM");
    String xlogpos = null;
    if (resultSet.next()) {
        xlogpos = resultSet.getString(3);
    }
    resultSet.close();
    statement.close();
    assertThat("Replication protocol supports a limited number of commands, " + "and it command can be execute via Statement(simple query protocol), " + "and result fetch via ResultSet", xlogpos, CoreMatchers.notNullValue());
}
Example 68
Project: piraso-master  File: PreferencesTest.java View source code
@Test
public void testAddProperty() throws Exception {
    Preferences preferences = new Preferences();
    preferences.addProperty("1", 1);
    preferences.addProperty("true", true);
    assertThat(preferences.isEnabled("true"), is(true));
    assertThat(preferences.isEnabled("not existing"), is(false));
    assertThat(preferences.getIntValue("1"), is(1));
    assertThat(preferences.getIntValue("not existsing"), CoreMatchers.<Object>nullValue());
}
Example 69
Project: qi4j-sdk-master  File: UnitOfWorkFactoryTest.java View source code
@Test
public void testUnitOfWork() throws Exception {
    UnitOfWork unitOfWork = module.newUnitOfWork();
    // Create product
    EntityBuilder<ProductEntity> cb = unitOfWork.newEntityBuilder(ProductEntity.class);
    cb.instance().name().set("Chair");
    cb.instance().price().set(57);
    Product chair = cb.newInstance();
    String actual = chair.name().get();
    org.junit.Assert.assertThat("Chair.name()", actual, org.hamcrest.CoreMatchers.equalTo("Chair"));
    org.junit.Assert.assertThat("Chair.price()", chair.price().get(), org.hamcrest.CoreMatchers.equalTo(57));
    unitOfWork.complete();
}
Example 70
Project: SmartHome-master  File: EnrichThingDTOMapperTest.java View source code
@Test
public void shouldMapEnrichedThingDTO() {
    when(linkedItemsMap.get("1")).thenReturn(Sets.newHashSet("linkedItem1", "linkedItem2"));
    EnrichedThingDTO enrichedThingDTO = EnrichedThingDTOMapper.map(thing, thingStatusInfo, firmwareStatus, linkedItemsMap, true);
    assertThat(enrichedThingDTO.editable, is(true));
    assertThat(enrichedThingDTO.firmwareStatus, is(equalTo(firmwareStatus)));
    assertThat(enrichedThingDTO.statusInfo, is(equalTo(thingStatusInfo)));
    assertThat(enrichedThingDTO.thingTypeUID, is(equalTo(thing.getThingTypeUID().getAsString())));
    assertThat(enrichedThingDTO.label, is(equalTo(THING_LABEL)));
    assertThat(enrichedThingDTO.bridgeUID, is(CoreMatchers.nullValue()));
    assertChannels(enrichedThingDTO);
    assertThat(enrichedThingDTO.configuration.values(), is(empty()));
    assertThat(enrichedThingDTO.properties, is(equalTo(properties)));
    assertThat(enrichedThingDTO.location, is(equalTo(LOCATION)));
}
Example 71
Project: spring-hateoas-master  File: ControllerEntityLinksUnitTest.java View source code
/**
	 * @see #43
	 */
@Test
@SuppressWarnings("unchecked")
public void returnsLinkBuilderForParameterizedController() {
    when(linkBuilderFactory.linkTo(eq(ControllerWithParameters.class), Mockito.any(Object[].class))).thenReturn(linkTo(ControllerWithParameters.class, "1"));
    ControllerEntityLinks links = new ControllerEntityLinks(Arrays.asList(ControllerWithParameters.class), linkBuilderFactory);
    LinkBuilder builder = links.linkFor(Order.class, "1");
    assertThat(builder.withSelfRel().getHref(), CoreMatchers.endsWith("/person/1"));
}
Example 72
Project: 3House-master  File: GeneralTest.java View source code
@Test
public void testOpenSettings() {
    NavigationUtil.navigateToSettings();
    onView(withText(R.string.settings_general)).perform(ViewActions.click());
    ViewInteraction cbxLoadLast = onView(withText(R.string.open_last_sitemap_on_upstart));
    cbxLoadLast.check(ViewAssertions.matches(CoreMatchers.not(isChecked())));
    cbxLoadLast.perform(ViewActions.click());
    cbxLoadLast.check(ViewAssertions.matches(isChecked()));
    cbxLoadLast.perform(ViewActions.click());
    cbxLoadLast.check(ViewAssertions.matches(CoreMatchers.not(isChecked())));
}
Example 73
Project: aerogear-simplepush-server-master  File: MessageFrameTest.java View source code
@Test
public void messages() {
    final String[] messages = { "one", "two", "three" };
    final MessageFrame messageFrame = new MessageFrame(messages);
    assertThat(messageFrame.messages().size(), CoreMatchers.is(3));
    assertThat(messageFrame.messages(), CoreMatchers.hasItems("one", "two", "three"));
    messageFrame.release();
}
Example 74
Project: android-priority-jobqueue-examples-master  File: SqliteJobQueueTest.java View source code
@Test
public void testCustomSerializer() throws Exception {
    final CountDownLatch calledForSerialize = new CountDownLatch(1);
    final CountDownLatch calledForDeserialize = new CountDownLatch(1);
    SqliteJobQueue.JobSerializer jobSerializer = new SqliteJobQueue.JavaSerializer() {

        @Override
        public byte[] serialize(Object object) throws IOException {
            calledForSerialize.countDown();
            return super.serialize(object);
        }

        @Override
        public <T extends BaseJob> T deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
            calledForDeserialize.countDown();
            return super.deserialize(bytes);
        }
    };
    SqliteJobQueue jobQueue = new SqliteJobQueue(Robolectric.application, System.nanoTime(), "__" + System.nanoTime(), jobSerializer);
    jobQueue.insert(createNewJobHolder(new Params(0)));
    calledForSerialize.await(1, TimeUnit.SECONDS);
    MatcherAssert.assertThat("custom serializer should be called for serialize", (int) calledForSerialize.getCount(), CoreMatchers.equalTo(0));
    MatcherAssert.assertThat("custom serializer should NOT be called for deserialize", (int) calledForDeserialize.getCount(), CoreMatchers.equalTo(1));
    jobQueue.nextJobAndIncRunCount(true, null);
    MatcherAssert.assertThat("custom serializer should be called for deserialize", (int) calledForDeserialize.getCount(), CoreMatchers.equalTo(0));
}
Example 75
Project: android-priority-jobqueue-master  File: SqliteJobQueueTest.java View source code
@Test
public void testCustomSerializer() throws Exception {
    final CountDownLatch calledForSerialize = new CountDownLatch(1);
    final CountDownLatch calledForDeserialize = new CountDownLatch(1);
    SqliteJobQueue.JobSerializer jobSerializer = new SqliteJobQueue.JavaSerializer() {

        @Override
        public byte[] serialize(Object object) throws IOException {
            calledForSerialize.countDown();
            return super.serialize(object);
        }

        @Override
        public <T extends BaseJob> T deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
            calledForDeserialize.countDown();
            return super.deserialize(bytes);
        }
    };
    SqliteJobQueue jobQueue = new SqliteJobQueue(Robolectric.application, System.nanoTime(), "__" + System.nanoTime(), jobSerializer);
    jobQueue.insert(createNewJobHolder(new Params(0)));
    calledForSerialize.await(1, TimeUnit.SECONDS);
    MatcherAssert.assertThat("custom serializer should be called for serialize", (int) calledForSerialize.getCount(), CoreMatchers.equalTo(0));
    MatcherAssert.assertThat("custom serializer should NOT be called for deserialize", (int) calledForDeserialize.getCount(), CoreMatchers.equalTo(1));
    jobQueue.nextJobAndIncRunCount(true, null);
    MatcherAssert.assertThat("custom serializer should be called for deserialize", (int) calledForDeserialize.getCount(), CoreMatchers.equalTo(0));
}
Example 76
Project: approval-master  File: ExecutableExistsOnPathTest.java View source code
@Test
public void shouldProperlyExecuteOnUnix() throws Exception {
    CrossPlatformCommand.setOS("Linux");
    Assert.assertThat(new ExecutableExistsOnPath("non-existing-executable").execute(), CoreMatchers.equalTo(false));
    Assume.assumeTrue(CrossPlatformCommand.isUnix());
    Assert.assertThat(new ExecutableExistsOnPath("vim").execute(), CoreMatchers.equalTo(true));
}
Example 77
Project: atam4j-master  File: Atam4jIntegrationTest.java View source code
private void checkThatWeEventuallyGetSuccess(TestStatusResource resource) {
    PollingPredicate<TestsRunResult> resultPollingPredicate = new PollingPredicate<>(UnitTestTimeouts.MAX_ATTEMPTS, UnitTestTimeouts.RETRY_POLL_INTERVAL_IN_MILLIS,  testsRunResult -> testsRunResult.getStatus().equals(TestsRunResult.Status.ALL_OK), () -> (TestsRunResult) resource.getTestStatus().getEntity());
    assertThat(resultPollingPredicate.pollUntilPassedOrMaxAttemptsExceeded(), CoreMatchers.is(true));
}
Example 78
Project: camelinaction2-master  File: FirstWildFlyIT.java View source code
@Test
public void testHello() throws Exception {
    // assume jboss is running
    String home = System.getenv("JBOSS_HOME");
    assumeThat("JBoss WildFly must be installed in JBOSS_HOME directory", home, CoreMatchers.anything(home));
    String out = camelContext.createProducerTemplate().requestBody("direct:hello", "Donald", String.class);
    assertEquals("Hello Donald", out);
}
Example 79
Project: cometd-master  File: CometDDisconnectSynchronousTest.java View source code
@Test
public void testDisconnectSynchronous() throws Exception {
    defineClass(Latch.class);
    evaluateScript("var readyLatch = new Latch(1);");
    Latch readyLatch = get("readyLatch");
    evaluateScript("" + "cometd.configure({url: '" + cometdURL + "', logLevel: '" + getLogLevel() + "'});" + "cometd.addListener('/meta/connect', function(message) { readyLatch.countDown(); });" + "" + "cometd.handshake();");
    Assert.assertTrue(readyLatch.await(5000));
    Assume.assumeThat((String) evaluateScript("cometd.getTransport().getType()"), CoreMatchers.equalTo("long-polling"));
    evaluateScript("" + "var disconnected = false;" + "cometd.addListener('/meta/disconnect', function(message) { disconnected = true; });" + "cometd.disconnect(true);" + "window.assert(disconnected === true);" + "");
}
Example 80
Project: dataflow-java-master  File: PairGeneratorTest.java View source code
@Test
public void testAllPairsWithReplacement() {
    FluentIterable<KV<String, String>> pairs = PairGenerator.WITH_REPLACEMENT.allPairs(ImmutableList.of("one", "two", "three"), String.CASE_INSENSITIVE_ORDER);
    assertEquals(6, pairs.size());
    assertThat(pairs, CoreMatchers.hasItems(KV.of("one", "one"), KV.of("one", "two"), KV.of("one", "three"), KV.of("two", "two"), KV.of("three", "two"), KV.of("three", "three")));
}
Example 81
Project: doctester-master  File: ApplicationControllerTest.java View source code
@Test
public void testThatHeadRequestIsSent() {
    // /redirect will send a location: redirect in the headers
    Response result = makeRequest(Request.HEAD().url(testServerUrl().path("/")));
    assertThat(result.headers, CoreMatchers.notNullValue());
    assertThat(result.payload, CoreMatchers.nullValue());
    //ninja server not yet supporting HEAD
    assertThat(result.httpStatus, CoreMatchers.equalTo(404));
}
Example 82
Project: dungeon-master  File: WeatherTest.java View source code
@Test
public void testWeatherShouldPresentAllConditionsOverTheCourseOfAYear() {
    // Note that this test may fail because of probabilistic issues.
    // However, that would indicate an issue with conditions not varying enough, which would be a bug.
    Date date = new Date(10, 1, 1);
    final Date end = date.plus(1, DungeonTimeUnit.YEAR);
    Set<WeatherCondition> conditionSet = new HashSet<>();
    Weather weather = new Weather(date);
    while (date.compareTo(end) < 0) {
        // Check until a full year passes.
        conditionSet.add(weather.getCurrentCondition(date));
        // Check the condition hourly.
        date = date.plus(1, DungeonTimeUnit.HOUR);
    }
    Assert.assertThat(conditionSet, CoreMatchers.hasItems(WeatherCondition.values()));
}
Example 83
Project: email-ext-plugin-master  File: RecipientProviderTest.java View source code
@Test
public void allSupporting() throws Exception {
    List<RecipientProviderDescriptor> descriptors = RecipientProvider.allSupporting(WorkflowJob.class);
    assertThat(descriptors, CoreMatchers.hasItem(CoreMatchers.isA(DevelopersRecipientProvider.DescriptorImpl.class)));
    assertThat(descriptors, CoreMatchers.not(CoreMatchers.hasItem(CoreMatchers.isA(ListRecipientProvider.DescriptorImpl.class))));
    descriptors = RecipientProvider.allSupporting(FreeStyleProject.class);
    assertThat(descriptors, CoreMatchers.hasItem(CoreMatchers.isA(DevelopersRecipientProvider.DescriptorImpl.class)));
    assertThat(descriptors, CoreMatchers.hasItem(CoreMatchers.isA(ListRecipientProvider.DescriptorImpl.class)));
}
Example 84
Project: Inside_Android_Testing-master  File: ApiGatewayTest.java View source code
@Test
public void shouldMakeRemoteGetCalls() {
    Robolectric.getBackgroundScheduler().pause();
    TestGetRequest apiRequest = new TestGetRequest();
    apiGateway.makeRequest(apiRequest, responseCallbacks);
    Robolectric.addPendingHttpResponse(200, GENERIC_XML);
    Robolectric.getBackgroundScheduler().runOneTask();
    HttpRequestInfo sentHttpRequestData = Robolectric.getSentHttpRequestInfo(0);
    HttpRequest sentHttpRequest = sentHttpRequestData.getHttpRequest();
    assertThat(sentHttpRequest.getRequestLine().getUri(), equalTo("www.example.com"));
    assertThat(sentHttpRequest.getRequestLine().getMethod(), equalTo(HttpGet.METHOD_NAME));
    assertThat(sentHttpRequest.getHeaders("foo")[0].getValue(), equalTo("bar"));
    CredentialsProvider credentialsProvider = (CredentialsProvider) sentHttpRequestData.getHttpContext().getAttribute(ClientContext.CREDS_PROVIDER);
    assertThat(credentialsProvider.getCredentials(AuthScope.ANY).getUserPrincipal().getName(), CoreMatchers.equalTo("spongebob"));
    assertThat(credentialsProvider.getCredentials(AuthScope.ANY).getPassword(), CoreMatchers.equalTo("squarepants"));
}
Example 85
Project: jenkins-plugins-master  File: RecipientProviderTest.java View source code
@Test
public void allSupporting() throws Exception {
    List<RecipientProviderDescriptor> descriptors = RecipientProvider.allSupporting(WorkflowJob.class);
    assertThat(descriptors, CoreMatchers.hasItem(CoreMatchers.isA(DevelopersRecipientProvider.DescriptorImpl.class)));
    assertThat(descriptors, CoreMatchers.not(CoreMatchers.hasItem(CoreMatchers.isA(ListRecipientProvider.DescriptorImpl.class))));
    descriptors = RecipientProvider.allSupporting(FreeStyleProject.class);
    assertThat(descriptors, CoreMatchers.hasItem(CoreMatchers.isA(DevelopersRecipientProvider.DescriptorImpl.class)));
    assertThat(descriptors, CoreMatchers.hasItem(CoreMatchers.isA(ListRecipientProvider.DescriptorImpl.class)));
}
Example 86
Project: jetbrick-commons-master  File: ConfigTest.java View source code
@Test
public void testObject() {
    Assert.assertThat(c.asObject("webapp.formatter"), CoreMatchers.instanceOf(java.text.SimpleDateFormat.class));
    Thread thread1 = c.asObject("webapp.thread.1", Thread.class);
    Assert.assertEquals("jetbrick_demo_webapp", thread1.getName());
    Assert.assertEquals(Boolean.TRUE, thread1.isDaemon());
    Assert.assertEquals(5, thread1.getPriority());
    Thread thread2 = c.asObject("webapp.thread.2", Thread.class);
    Assert.assertTrue(thread1 == thread2);
}
Example 87
Project: Nin-master  File: RouteTest.java View source code
@Test
public void convertRawUriToRegex() {
    assertThat(Route.convertRawUriToRegex("/me/{username: .*}"), CoreMatchers.equalTo("/me/(.*)"));
    assertThat(Route.convertRawUriToRegex("/me/{username: [a-zA-Z][a-zA-Z_0-9]}"), CoreMatchers.equalTo("/me/([a-zA-Z][a-zA-Z_0-9])"));
    assertThat(Route.convertRawUriToRegex("/me/{username}"), CoreMatchers.equalTo("/me/([^/]*)"));
    // check regex with escapes/backslashes (\)
    assertThat(Route.convertRawUriToRegex("/me/{id: \\d+}"), CoreMatchers.equalTo("/me/(\\d+)"));
    // check regex with groups, they should be converted to non-capturing groups
    // people may want to have both "/users/mike" and "/mike" in one route
    // https://github.com/ninjaframework/ninja/issues/497
    assertThat(Route.convertRawUriToRegex("(/users)?/{user}"), CoreMatchers.equalTo("(?:/users)?/([^/]*)"));
}
Example 88
Project: Ninja-master  File: RouteTest.java View source code
@Test
public void convertRawUriToRegex() {
    assertThat(Route.convertRawUriToRegex("/me/{username: .*}"), CoreMatchers.equalTo("/me/(.*)"));
    assertThat(Route.convertRawUriToRegex("/me/{username: [a-zA-Z][a-zA-Z_0-9]}"), CoreMatchers.equalTo("/me/([a-zA-Z][a-zA-Z_0-9])"));
    assertThat(Route.convertRawUriToRegex("/me/{username}"), CoreMatchers.equalTo("/me/([^/]*)"));
    // check regex with escapes/backslashes (\)
    assertThat(Route.convertRawUriToRegex("/me/{id: \\d+}"), CoreMatchers.equalTo("/me/(\\d+)"));
    // check regex with groups, they should be converted to non-capturing groups
    // people may want to have both "/users/mike" and "/mike" in one route
    // https://github.com/ninjaframework/ninja/issues/497
    assertThat(Route.convertRawUriToRegex("(/users)?/{user}"), CoreMatchers.equalTo("(?:/users)?/([^/]*)"));
}
Example 89
Project: NuBitsj-master  File: TransactionOutputTest.java View source code
@Test
public void testMultiSigOutputToString() throws Exception {
    sendMoneyToWallet(Coin.COIN.add(Coin.CENT), AbstractBlockChain.NewBlockType.BEST_CHAIN);
    ECKey myKey = new ECKey();
    this.wallet.importKey(myKey);
    // Simulate another signatory
    ECKey otherKey = new ECKey();
    // Create multi-sig transaction
    Transaction multiSigTransaction = new Transaction(params);
    ImmutableList<ECKey> keys = ImmutableList.of(myKey, otherKey);
    Script scriptPubKey = ScriptBuilder.createMultiSigOutputScript(2, keys);
    multiSigTransaction.addOutput(Coin.COIN, scriptPubKey);
    Wallet.SendRequest req = Wallet.SendRequest.forTx(multiSigTransaction);
    this.wallet.completeTx(req);
    TransactionOutput multiSigTransactionOutput = multiSigTransaction.getOutput(0);
    assertThat(multiSigTransactionOutput.toString(), CoreMatchers.containsString("CHECKMULTISIG"));
}
Example 90
Project: Orekit-master  File: NegateDetectorTest.java View source code
/**
     * check g function is negated.
     *
     * @throws OrekitException on error
     */
@Test
public void testG() throws OrekitException {
    //setup
    EventDetector a = Mockito.mock(EventDetector.class);
    NegateDetector detector = new NegateDetector(a);
    SpacecraftState s = Mockito.mock(SpacecraftState.class);
    // verify + to -
    Mockito.when(a.g(s)).thenReturn(1.0);
    Assert.assertThat(detector.g(s), CoreMatchers.is(-1.0));
    // verify - to +
    Mockito.when(a.g(s)).thenReturn(-1.0);
    Assert.assertThat(detector.g(s), CoreMatchers.is(1.0));
}
Example 91
Project: Resteasy-master  File: UndertowTest.java View source code
/**
     * @tpTestDetails Redirection in one servlet to other servlet.
     * @tpSince RESTEasy 3.0.16
     */
@Test
public void testUndertow() throws Exception {
    URL url = new URL(generateURL("/test"));
    HttpURLConnection conn = HttpURLConnection.class.cast(url.openConnection());
    conn.connect();
    byte[] b = new byte[16];
    conn.getInputStream().read(b);
    Assert.assertThat("Wrong content of response", new String(b), CoreMatchers.startsWith("forward"));
    Assert.assertEquals(HttpResponseCodes.SC_OK, conn.getResponseCode());
    conn.disconnect();
}
Example 92
Project: rxnorm-client-master  File: RxNormSuggestionGroupTest.java View source code
@Test
public void testDeserializeRelatedGroupResponse() throws IOException {
    ClassLoader cl = NdfrtGroupConceptTest.class.getClassLoader();
    File testJsonResponseFile = new File(cl.getResource("json/rxnorm-related-response.json").getFile());
    FileReader jsonStreamReader = new FileReader(testJsonResponseFile);
    AllRelatedGroupResponse response = gson.fromJson(jsonStreamReader, AllRelatedGroupResponse.class);
    jsonStreamReader.close();
    List<ConceptGroup> relatedGroup = response.getAllRelatedGroup().getConceptGroup();
    assertThat("We received 16 relationships", relatedGroup.size(), CoreMatchers.is(16));
    //Make sure that we get at least one ConceptProperty from the set
    boolean didReceiveProperties = false;
    for (ConceptGroup cg : relatedGroup) {
        assertThat("ConceptGroup is not null", cg, Matchers.notNullValue());
        assertThat("ConceptGroup is TTY is set", cg.getTty(), Matchers.notNullValue());
        for (ConceptProperty property : cg.getConceptProperties()) {
            didReceiveProperties = true;
            assertThat("Property name is set", property.getName(), Matchers.notNullValue());
            assertThat("Property TTY is set", property.getTty(), Matchers.notNullValue());
            assertThat("Property langugage is set", property.getLanguage(), Matchers.notNullValue());
            assertThat("Property rxcui is set", property.getRxcui(), Matchers.notNullValue());
        }
    }
    assertThat("We saw at least one concept property set", didReceiveProperties, Matchers.is(true));
    assertThat("The rxnormId query is 866350", response.getAllRelatedGroup().getRxcui(), Matchers.equalToIgnoringCase("866350"));
}
Example 93
Project: sagan-master  File: GuidesOrgTests.java View source code
@Test
public void shouldFindByPrefix() throws Exception {
    given(ghClient.sendRequestForJson(anyString(), anyVararg())).willReturn(Fixtures.githubRepoListJson());
    List<GitHubRepo> matches = service.findRepositoriesByPrefix(GettingStartedGuides.REPO_PREFIX);
    assertThat(matches.size(), greaterThan(0));
    for (GitHubRepo match : matches) {
        assertThat(match.getName(), CoreMatchers.startsWith(GettingStartedGuides.REPO_PREFIX));
    }
}
Example 94
Project: streamflow-core-master  File: StringsTest.java View source code
@Test
public void testEmpty() {
    Assert.assertThat(Strings.empty(null), CoreMatchers.equalTo(true));
    Assert.assertThat(Strings.empty(""), CoreMatchers.equalTo(true));
    Assert.assertThat(Strings.empty(" "), CoreMatchers.equalTo(true));
    Assert.assertThat(Strings.empty("X "), CoreMatchers.equalTo(false));
    Assert.assertThat(Strings.empty("X"), CoreMatchers.equalTo(false));
}
Example 95
Project: terasoluna-gfw-master  File: BusinessExceptionTest.java View source code
@Test
public void testConstructor2() throws Exception {
    String message = "resultMessages";
    Exception cause = new IllegalArgumentException("cause");
    // expect
    expectedException.expect(BusinessException.class);
    expectedException.expectMessage(message);
    Matcher<? extends Throwable> matcher = CoreMatchers.instanceOf(IllegalArgumentException.class);
    expectedException.expectCause(matcher);
    // set up
    ResultMessages resultMessages = ResultMessages.error().add(ResultMessage.fromText(message));
    exception = new BusinessException(resultMessages, cause);
    // throw & assert
    throw exception;
}
Example 96
Project: Yggdrasil-master  File: RunStateTest.java View source code
@Test
public void testReadRunState() throws Exception {
    if (TravisUtils.runningOnTravis()) {
        return;
    }
    RunState runnableRunState = new RunState();
    Thread runstate = new Thread(runnableRunState);
    runstate.start();
    // Get host name where the service should run.
    HostName hostname = new HostName();
    String hn = hostname.getHostName();
    // Set port
    YggdrasilConfig config = new YggdrasilConfig(generalConfigFile);
    int MONITOR_PORT = config.getMonitorPort();
    logger.info("RunStateTest: " + hn + ":" + MONITOR_PORT);
    Socket socket = new Socket(hn, MONITOR_PORT);
    // Read run state form endpoint
    BufferedReader rd = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    try {
        Assert.assertNotNull(rd);
        String runStateText = rd.readLine();
        Assert.assertThat(runStateText, CoreMatchers.containsString("Yggdrasil"));
    } finally {
        rd.close();
        socket.close();
    }
}
Example 97
Project: hibernate-semantic-query-master  File: SelectClauseTests.java View source code
@Test
public void testNestedDynamicInstantiationSelection() {
    SqmSelectStatement statement = interpretSelect("select new org.hibernate.sqm.test.hql.SelectClauseTests$DTO(" + "    p.nickName, " + "    p.numberOfToes, " + "    new org.hibernate.sqm.test.hql.SelectClauseTests$DTO(p.nickName, p.numberOfToes) " + " ) " + "from Person p");
    assertEquals(1, statement.getQuerySpec().getSelectClause().getSelections().size());
    assertThat(statement.getQuerySpec().getSelectClause().getSelections().get(0).getExpression(), instanceOf(SqmDynamicInstantiation.class));
    SqmDynamicInstantiation dynamicInstantiation = (SqmDynamicInstantiation) statement.getQuerySpec().getSelectClause().getSelections().get(0).getExpression();
    assertThat(dynamicInstantiation.getInstantiationTarget().getNature(), equalTo(SqmDynamicInstantiationTarget.Nature.CLASS));
    assertThat(dynamicInstantiation.getInstantiationTarget().getJavaType(), CoreMatchers.<Class>equalTo(DTO.class));
    assertEquals(3, dynamicInstantiation.getArguments().size());
    assertThat(dynamicInstantiation.getArguments().get(0).getExpression(), instanceOf(SqmSingularAttributeReference.class));
    assertThat(dynamicInstantiation.getArguments().get(1).getExpression(), instanceOf(SqmSingularAttributeReference.class));
    assertThat(dynamicInstantiation.getArguments().get(2).getExpression(), instanceOf(SqmDynamicInstantiation.class));
    SqmDynamicInstantiation nestedInstantiation = (SqmDynamicInstantiation) dynamicInstantiation.getArguments().get(2).getExpression();
    assertThat(nestedInstantiation.getInstantiationTarget().getNature(), equalTo(SqmDynamicInstantiationTarget.Nature.CLASS));
    assertThat(nestedInstantiation.getInstantiationTarget().getJavaType(), CoreMatchers.<Class>equalTo(DTO.class));
}
Example 98
Project: iosched-master  File: SessionDetailActivity_EndedLiveSessionTest.java View source code
@Test
public void youTubeVideo_WhenClicked_IntentFired() {
    Intent resultData = new Intent();
    resultData.putExtras(new Bundle());
    // Create the ActivityResult with the Intent.
    Intents.intending(CoreMatchers.not(IntentMatchers.isInternal())).respondWith(new Instrumentation.ActivityResult(Activity.RESULT_OK, resultData));
    // When clicking on video
    onView(withId(R.id.watch)).perform(click());
    // Then the intent to play the video is fired
    IntentUtils.checkVideoIntentIsFired(SessionsMockCursor.FAKE_YOUTUBE_URL, mActivityRule.getActivity(), false);
}
Example 99
Project: jobConfigHistory-plugin-master  File: JobConfigHistoryBaseActionIT.java View source code
@Bug(5534)
public void testSecuredAccessToJobConfigHistoryPage() throws IOException, SAXException {
    // without security the jobConfigHistory-badge should show.
    final HtmlPage withoutSecurity = webClient.goTo("/");
    assertThat(withoutSecurity.asXml(), CoreMatchers.containsString(JobConfigHistoryConsts.ICONFILENAME));
    withoutSecurity.getAnchorByHref("/" + JobConfigHistoryConsts.URLNAME);
    // with security enabled the jobConfigHistory-badge should not show
    // anymore.
    jenkins.setSecurityRealm(new HudsonPrivateSecurityRealm(false, false, null));
    jenkins.setAuthorizationStrategy(new LegacyAuthorizationStrategy());
    final HtmlPage withSecurityEnabled = webClient.goTo("/");
    assertThat(withSecurityEnabled.asXml(), not(CoreMatchers.containsString(JobConfigHistoryConsts.ICONFILENAME)));
    try {
        withSecurityEnabled.getAnchorByHref("/" + JobConfigHistoryConsts.URLNAME);
        Assert.fail("Expected a " + ElementNotFoundException.class + " to be thrown");
    } catch (ElementNotFoundException e) {
        System.err.println(e);
    }
}
Example 100
Project: opslogger-master  File: OpsLoggerTestDouble.java View source code
private void validate(T message) {
    assertNotNull("LogMessage must be provided", message);
    assertNotNull("MessageCode must be provided", message.getMessageCode());
    assertThat("MessageCode must be provided", message.getMessageCode(), CoreMatchers.not(""));
    assertNotNull("MessagePattern must be provided", message.getMessagePattern());
    assertThat("MessagePattern must be provided", message.getMessagePattern(), CoreMatchers.not(""));
}
Example 101
Project: org.ops4j.pax.exam2-master  File: UserProbeTest.java View source code
/**
     * Gets books.html which contains the list of books in a library.
     * <p>
     * The html content is based on the defined books.jsp in the sample web module.
     */
@Test
public void testGetBooksHttpContent() throws Exception {
    HttpGet httpGet = new HttpGet("http://localhost:9080" + ContainerConstants.EXAM_CONTEXT_ROOT + "/books.html");
    try (CloseableHttpClient httpclient = HttpClients.createDefault();
        CloseableHttpResponse response = httpclient.execute(httpGet)) {
        assertThat("Status code must be 200 - OK", response.getStatusLine().getStatusCode(), is(200));
        // verify html content
        String content = EntityUtils.toString(response.getEntity());
        assertThat(content, is(notNullValue()));
        // TODO Why does CoreMatchers.containsString() not work?
        assertThat(content.contains("Steinbeck"), is(true));
    }
}