src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
LongDataItem implements DataItem { @Override public Short getShort() { return value.shortValue(); } LongDataItem(); LongDataItem(final long value); @Override Boolean getBoolean(); @Override Byte getByte(); @Override Integer getInteger(); @Override Short getShort(); @Override Long getLong(); @Override String getString(); @Override Double getDouble(); @Override Comparable getComparable(); @Override int compareTo(final Object o); @Override boolean equals(final Object o); @Override int hashCode(); @Override void write(final DataOutput out); @Override void readFields(final DataInput in); @Override String toString(); @Override byte getThriftType(); }
@Test(groups = "fast") public void testConvertToShort() throws Exception { Assert.assertEquals(value0.getShort(), Short.valueOf((short) 0)); Assert.assertEquals(value1.getShort(), Short.valueOf((short) 1)); Assert.assertEquals(valueBigPositive.getShort(), Short.valueOf((short) -7168)); Assert.assertEquals(valueBigNegative.getShort(), Short.valueOf((short) 7168)); }
LongDataItem implements DataItem { @Override public Integer getInteger() { return value.intValue(); } LongDataItem(); LongDataItem(final long value); @Override Boolean getBoolean(); @Override Byte getByte(); @Override Integer getInteger(); @Override Short getShort(); @Override Long getLong(); @Override String getString(); @Override Double getDouble(); @Override Comparable getComparable(); @Override int compareTo(final Object o); @Override boolean equals(final Object o); @Override int hashCode(); @Override void write(final DataOutput out); @Override void readFields(final DataInput in); @Override String toString(); @Override byte getThriftType(); }
@Test(groups = "fast") public void testConvertToInteger() throws Exception { Assert.assertEquals(value0.getInteger(), Integer.valueOf(0)); Assert.assertEquals(value1.getInteger(), Integer.valueOf(1)); Assert.assertEquals(valueBigPositive.getInteger(), Integer.valueOf(1410065408)); Assert.assertEquals(valueBigNegative.getInteger(), Integer.valueOf(-1410065408)); }
LongDataItem implements DataItem { @Override public Double getDouble() { return value.doubleValue(); } LongDataItem(); LongDataItem(final long value); @Override Boolean getBoolean(); @Override Byte getByte(); @Override Integer getInteger(); @Override Short getShort(); @Override Long getLong(); @Override String getString(); @Override Double getDouble(); @Override Comparable getComparable(); @Override int compareTo(final Object o); @Override boolean equals(final Object o); @Override int hashCode(); @Override void write(final DataOutput out); @Override void readFields(final DataInput in); @Override String toString(); @Override byte getThriftType(); }
@Test(groups = "fast") public void testConvertToDouble() throws Exception { Assert.assertEquals(value0.getDouble(), 0.0); Assert.assertEquals(value1.getDouble(), 1.0); Assert.assertEquals(valueBigPositive.getDouble(), 10000000000.0); Assert.assertEquals(valueBigNegative.getDouble(), -10000000000.0); }
LongDataItem implements DataItem { @Override public String getString() { return String.valueOf(value); } LongDataItem(); LongDataItem(final long value); @Override Boolean getBoolean(); @Override Byte getByte(); @Override Integer getInteger(); @Override Short getShort(); @Override Long getLong(); @Override String getString(); @Override Double getDouble(); @Override Comparable getComparable(); @Override int compareTo(final Object o); @Override boolean equals(final Object o); @Override int hashCode(); @Override void write(final DataOutput out); @Override void readFields(final DataInput in); @Override String toString(); @Override byte getThriftType(); }
@Test(groups = "fast") public void testConvertToStringOk() throws Exception { Assert.assertEquals(value0.getString(), "0"); Assert.assertEquals(value1.getString(), "1"); Assert.assertEquals(valueBigPositive.getString(), "10000000000"); Assert.assertEquals(valueBigNegative.getString(), "-10000000000"); }
LongDataItem implements DataItem { @Override public String toString() { return getString(); } LongDataItem(); LongDataItem(final long value); @Override Boolean getBoolean(); @Override Byte getByte(); @Override Integer getInteger(); @Override Short getShort(); @Override Long getLong(); @Override String getString(); @Override Double getDouble(); @Override Comparable getComparable(); @Override int compareTo(final Object o); @Override boolean equals(final Object o); @Override int hashCode(); @Override void write(final DataOutput out); @Override void readFields(final DataInput in); @Override String toString(); @Override byte getThriftType(); }
@Test(groups = "fast") public void testToString() throws Exception { Assert.assertEquals(value0.toString(), "0"); Assert.assertEquals(value1.toString(), "1"); Assert.assertEquals(valueBigPositive.toString(), "10000000000"); Assert.assertEquals(valueBigNegative.toString(), "-10000000000"); }
ShortDataItem implements DataItem { @Override public Short getShort() { return value; } ShortDataItem(); ShortDataItem(final short value); @Override Boolean getBoolean(); @Override Byte getByte(); @Override Integer getInteger(); @Override Short getShort(); @Override Long getLong(); @Override String getString(); @Override Double getDouble(); @Override Comparable getComparable(); @Override int compareTo(final Object o); @Override boolean equals(final Object o); @Override int hashCode(); @Override void write(final DataOutput out); @Override void readFields(final DataInput in); @Override String toString(); @Override byte getThriftType(); }
@Test(groups = "fast") public void testNoArgConstructor() throws Exception { final DataItem item = new ShortDataItem(); Assert.assertEquals(item.getShort(), Short.valueOf((short) 0)); } @Test(groups = "fast") public void testConstructor() throws Exception { final DataItem item1 = new ShortDataItem((short) 100); Assert.assertEquals(item1.getShort(), Short.valueOf((short) 100)); } @Test(groups = "fast") public void testConvertToShort() throws Exception { Assert.assertEquals(value0.getShort(), Short.valueOf((short) 0)); Assert.assertEquals(value1.getShort(), Short.valueOf((short) 1)); Assert.assertEquals(value1000.getShort(), Short.valueOf((short) 1000)); Assert.assertEquals(valueMinus1000.getShort(), Short.valueOf((short) -1000)); }
ShortDataItem implements DataItem { @Override public Boolean getBoolean() { return !value.equals((short) 0); } ShortDataItem(); ShortDataItem(final short value); @Override Boolean getBoolean(); @Override Byte getByte(); @Override Integer getInteger(); @Override Short getShort(); @Override Long getLong(); @Override String getString(); @Override Double getDouble(); @Override Comparable getComparable(); @Override int compareTo(final Object o); @Override boolean equals(final Object o); @Override int hashCode(); @Override void write(final DataOutput out); @Override void readFields(final DataInput in); @Override String toString(); @Override byte getThriftType(); }
@Test(groups = "fast") public void testConvertToBoolean() throws Exception { Assert.assertEquals(value0.getBoolean().booleanValue(), false); Assert.assertEquals(value1.getBoolean().booleanValue(), true); Assert.assertEquals(value1000.getBoolean().booleanValue(), true); Assert.assertEquals(valueMinus1000.getBoolean().booleanValue(), true); }
ShortDataItem implements DataItem { @Override public Byte getByte() { return value.byteValue(); } ShortDataItem(); ShortDataItem(final short value); @Override Boolean getBoolean(); @Override Byte getByte(); @Override Integer getInteger(); @Override Short getShort(); @Override Long getLong(); @Override String getString(); @Override Double getDouble(); @Override Comparable getComparable(); @Override int compareTo(final Object o); @Override boolean equals(final Object o); @Override int hashCode(); @Override void write(final DataOutput out); @Override void readFields(final DataInput in); @Override String toString(); @Override byte getThriftType(); }
@Test(groups = "fast") public void testConvertToByte() throws Exception { Assert.assertEquals(value0.getByte(), Byte.valueOf((byte) 0)); Assert.assertEquals(value1.getByte(), Byte.valueOf((byte) 1)); Assert.assertEquals(value1000.getByte(), Byte.valueOf((byte) -24)); Assert.assertEquals(valueMinus1000.getByte(), Byte.valueOf((byte) 24)); }
ShortDataItem implements DataItem { @Override public Integer getInteger() { return value.intValue(); } ShortDataItem(); ShortDataItem(final short value); @Override Boolean getBoolean(); @Override Byte getByte(); @Override Integer getInteger(); @Override Short getShort(); @Override Long getLong(); @Override String getString(); @Override Double getDouble(); @Override Comparable getComparable(); @Override int compareTo(final Object o); @Override boolean equals(final Object o); @Override int hashCode(); @Override void write(final DataOutput out); @Override void readFields(final DataInput in); @Override String toString(); @Override byte getThriftType(); }
@Test(groups = "fast") public void testConvertToInteger() throws Exception { Assert.assertEquals(value0.getInteger(), Integer.valueOf(0)); Assert.assertEquals(value1.getInteger(), Integer.valueOf(1)); Assert.assertEquals(value1000.getInteger(), Integer.valueOf(1000)); Assert.assertEquals(valueMinus1000.getInteger(), Integer.valueOf(-1000)); }
ShortDataItem implements DataItem { @Override public Long getLong() { return value.longValue(); } ShortDataItem(); ShortDataItem(final short value); @Override Boolean getBoolean(); @Override Byte getByte(); @Override Integer getInteger(); @Override Short getShort(); @Override Long getLong(); @Override String getString(); @Override Double getDouble(); @Override Comparable getComparable(); @Override int compareTo(final Object o); @Override boolean equals(final Object o); @Override int hashCode(); @Override void write(final DataOutput out); @Override void readFields(final DataInput in); @Override String toString(); @Override byte getThriftType(); }
@Test(groups = "fast") public void testConvertToLong() throws Exception { Assert.assertEquals(value0.getLong(), Long.valueOf(0)); Assert.assertEquals(value1.getLong(), Long.valueOf(1)); Assert.assertEquals(value1000.getLong(), Long.valueOf(1000)); Assert.assertEquals(valueMinus1000.getLong(), Long.valueOf(-1000)); }
IntegerDataItem implements DataItem { @Override public Boolean getBoolean() { return !value.equals(0); } IntegerDataItem(); IntegerDataItem(final int value); @Override Boolean getBoolean(); @Override Byte getByte(); @Override Integer getInteger(); @Override Short getShort(); @Override Long getLong(); @Override String getString(); @Override Double getDouble(); @Override Comparable getComparable(); @Override int compareTo(final Object o); @Override boolean equals(final Object o); @Override int hashCode(); @Override void write(final DataOutput out); @Override void readFields(final DataInput in); @Override String toString(); @Override byte getThriftType(); }
@Test(groups = "fast") public void testConvertToBoolean() throws Exception { Assert.assertEquals(value0.getBoolean().booleanValue(), false); Assert.assertEquals(value1.getBoolean().booleanValue(), true); Assert.assertEquals(value1000000.getBoolean().booleanValue(), true); Assert.assertEquals(valueMinus1000000.getBoolean().booleanValue(), true); }
ShortDataItem implements DataItem { @Override public Double getDouble() { return value.doubleValue(); } ShortDataItem(); ShortDataItem(final short value); @Override Boolean getBoolean(); @Override Byte getByte(); @Override Integer getInteger(); @Override Short getShort(); @Override Long getLong(); @Override String getString(); @Override Double getDouble(); @Override Comparable getComparable(); @Override int compareTo(final Object o); @Override boolean equals(final Object o); @Override int hashCode(); @Override void write(final DataOutput out); @Override void readFields(final DataInput in); @Override String toString(); @Override byte getThriftType(); }
@Test(groups = "fast") public void testConvertToDouble() throws Exception { Assert.assertEquals(value0.getDouble(), 0.0); Assert.assertEquals(value1.getDouble(), 1.0); Assert.assertEquals(value1000.getDouble(), 1000.0); Assert.assertEquals(valueMinus1000.getDouble(), -1000.0); }
ShortDataItem implements DataItem { @Override public String getString() { return String.valueOf(value); } ShortDataItem(); ShortDataItem(final short value); @Override Boolean getBoolean(); @Override Byte getByte(); @Override Integer getInteger(); @Override Short getShort(); @Override Long getLong(); @Override String getString(); @Override Double getDouble(); @Override Comparable getComparable(); @Override int compareTo(final Object o); @Override boolean equals(final Object o); @Override int hashCode(); @Override void write(final DataOutput out); @Override void readFields(final DataInput in); @Override String toString(); @Override byte getThriftType(); }
@Test(groups = "fast") public void testConvertToStringOk() throws Exception { Assert.assertEquals(value0.getString(), "0"); Assert.assertEquals(value1.getString(), "1"); Assert.assertEquals(value1000.getString(), "1000"); Assert.assertEquals(valueMinus1000.getString(), "-1000"); }
ShortDataItem implements DataItem { @Override public String toString() { return getString(); } ShortDataItem(); ShortDataItem(final short value); @Override Boolean getBoolean(); @Override Byte getByte(); @Override Integer getInteger(); @Override Short getShort(); @Override Long getLong(); @Override String getString(); @Override Double getDouble(); @Override Comparable getComparable(); @Override int compareTo(final Object o); @Override boolean equals(final Object o); @Override int hashCode(); @Override void write(final DataOutput out); @Override void readFields(final DataInput in); @Override String toString(); @Override byte getThriftType(); }
@Test(groups = "fast") public void testToString() throws Exception { Assert.assertEquals(value0.toString(), "0"); Assert.assertEquals(value1.toString(), "1"); Assert.assertEquals(value1000.toString(), "1000"); Assert.assertEquals(valueMinus1000.toString(), "-1000"); }
StringDataItem implements DataItem { @Override public String getString() { return value; } StringDataItem(); StringDataItem(final String value); @Override Boolean getBoolean(); @Override Byte getByte(); @Override Integer getInteger(); @Override Short getShort(); @Override Long getLong(); @Override String getString(); @Override Double getDouble(); @Override Comparable getComparable(); @Override int compareTo(final Object o); @Override int hashCode(); @Override boolean equals(final Object o); @Override void write(final DataOutput out); @Override void readFields(final DataInput in); @Override String toString(); @Override byte getThriftType(); }
@Test(groups = "fast") public void testNoArgConstructor() throws Exception { final DataItem item = new StringDataItem(); Assert.assertEquals(item.getString(), ""); } @Test(groups = "fast") public void testConstructor() throws Exception { final String testString = "test-string"; final DataItem item1 = new StringDataItem(testString); Assert.assertEquals(item1.getString(), testString); }
StringDataItem implements DataItem { @Override public Double getDouble() { if (value.isEmpty()) { return (double) 0; } return Double.valueOf(value); } StringDataItem(); StringDataItem(final String value); @Override Boolean getBoolean(); @Override Byte getByte(); @Override Integer getInteger(); @Override Short getShort(); @Override Long getLong(); @Override String getString(); @Override Double getDouble(); @Override Comparable getComparable(); @Override int compareTo(final Object o); @Override int hashCode(); @Override boolean equals(final Object o); @Override void write(final DataOutput out); @Override void readFields(final DataInput in); @Override String toString(); @Override byte getThriftType(); }
@Test(groups = "fast") public void testConvertToDoubleOk() throws Exception { final long value1 = 1341345143; final DataItem item1 = new StringDataItem(String.valueOf(value1)); Assert.assertEquals(item1.getDouble(), (double) value1); final double value2 = 1341345143.13242142; final DataItem item2 = new StringDataItem(String.valueOf(value2)); Assert.assertEquals(item2.getDouble(), value2); } @Test(groups = "fast") public void testConvertToDoubleFail() throws Exception { try { final DataItem item = new StringDataItem("a string"); item.getDouble(); Assert.fail("expected NumberFormatException NOT thrown"); } catch (Exception e) { Assert.assertEquals(e.getClass(), NumberFormatException.class); } }
StringDataItem implements DataItem { @Override public Long getLong() { if (value.isEmpty()) { return (long) 0; } return Long.valueOf(value); } StringDataItem(); StringDataItem(final String value); @Override Boolean getBoolean(); @Override Byte getByte(); @Override Integer getInteger(); @Override Short getShort(); @Override Long getLong(); @Override String getString(); @Override Double getDouble(); @Override Comparable getComparable(); @Override int compareTo(final Object o); @Override int hashCode(); @Override boolean equals(final Object o); @Override void write(final DataOutput out); @Override void readFields(final DataInput in); @Override String toString(); @Override byte getThriftType(); }
@Test(groups = "fast") public void testConvertToLongOk() throws Exception { final long value = 7890; final DataItem item = new StringDataItem(String.valueOf(value)); Assert.assertEquals(item.getLong(), Long.valueOf(value)); } @Test(groups = "fast") public void testConvertToLongFail() throws Exception { try { final DataItem item = new StringDataItem("a string"); item.getLong(); Assert.fail("expected NumberFormatException NOT thrown"); } catch (Exception e) { Assert.assertEquals(e.getClass(), NumberFormatException.class); } }
StringDataItem implements DataItem { @Override public String toString() { return getString(); } StringDataItem(); StringDataItem(final String value); @Override Boolean getBoolean(); @Override Byte getByte(); @Override Integer getInteger(); @Override Short getShort(); @Override Long getLong(); @Override String getString(); @Override Double getDouble(); @Override Comparable getComparable(); @Override int compareTo(final Object o); @Override int hashCode(); @Override boolean equals(final Object o); @Override void write(final DataOutput out); @Override void readFields(final DataInput in); @Override String toString(); @Override byte getThriftType(); }
@Test(groups = "fast") public void testToString() throws Exception { final DataItem item = new StringDataItem("...a.a.sd.f...sf"); Assert.assertEquals(item.toString(), item.getString()); }
IntegerDataItem implements DataItem { @Override public Byte getByte() { return value.byteValue(); } IntegerDataItem(); IntegerDataItem(final int value); @Override Boolean getBoolean(); @Override Byte getByte(); @Override Integer getInteger(); @Override Short getShort(); @Override Long getLong(); @Override String getString(); @Override Double getDouble(); @Override Comparable getComparable(); @Override int compareTo(final Object o); @Override boolean equals(final Object o); @Override int hashCode(); @Override void write(final DataOutput out); @Override void readFields(final DataInput in); @Override String toString(); @Override byte getThriftType(); }
@Test(groups = "fast") public void testConvertToByte() throws Exception { Assert.assertEquals(value0.getByte(), Byte.valueOf((byte) 0)); Assert.assertEquals(value1.getByte(), Byte.valueOf((byte) 1)); Assert.assertEquals(value1000000.getByte(), Byte.valueOf((byte) 64)); Assert.assertEquals(valueMinus1000000.getByte(), Byte.valueOf((byte) -64)); }
ThriftEnvelopeEventToThrift { public static <T extends Serializable> T extractThrift(final Class<T> clazz, final ThriftEnvelopeEvent envelopeEvent) { final ThriftEnvelope envelope = (ThriftEnvelope) envelopeEvent.getData(); try { final T thriftObject = clazz.newInstance(); final Field[] fields = clazz.getFields(); for (final ThriftField tField : envelope.getPayload()) { if (tField.getId() >= fields.length) { continue; } final Field field = fields[tField.getId() - 1]; final Class<?> type = field.getType(); if (type.isAssignableFrom(Boolean.class)) { field.setBoolean(thriftObject, tField.getDataItem().getBoolean()); } else if (type.isAssignableFrom(boolean.class)) { field.setBoolean(thriftObject, tField.getDataItem().getBoolean()); } else if (type.isAssignableFrom(Byte.class)) { field.setByte(thriftObject, tField.getDataItem().getByte()); } else if (type.isAssignableFrom(byte.class)) { field.setByte(thriftObject, tField.getDataItem().getByte()); } else if (type.isAssignableFrom(Short.class)) { field.setShort(thriftObject, tField.getDataItem().getShort()); } else if (type.isAssignableFrom(short.class)) { field.setShort(thriftObject, tField.getDataItem().getShort()); } else if (type.isAssignableFrom(Integer.class)) { field.setInt(thriftObject, tField.getDataItem().getInteger()); } else if (type.isAssignableFrom(int.class)) { field.setInt(thriftObject, tField.getDataItem().getInteger()); } else if (type.isAssignableFrom(Long.class)) { field.setLong(thriftObject, tField.getDataItem().getLong()); } else if (type.isAssignableFrom(long.class)) { field.setLong(thriftObject, tField.getDataItem().getLong()); } else if (type.isAssignableFrom(Double.class)) { field.setDouble(thriftObject, tField.getDataItem().getDouble()); } else if (type.isAssignableFrom(double.class)) { field.setDouble(thriftObject, tField.getDataItem().getDouble()); } else if (type.isAssignableFrom(String.class)) { field.set(thriftObject, tField.getDataItem().getString()); } } return thriftObject; } catch (InstantiationException e) { return null; } catch (IllegalAccessException e) { return null; } } static T extractThrift(final Class<T> clazz, final ThriftEnvelopeEvent envelopeEvent); }
@Test public void testExtractThrift() throws Exception { final DateTime eventDateTime = new DateTime(); final String coreHostname = "hostname"; final TLoggingEvent event = new TLoggingEvent(); event.setCoreHostname(coreHostname); final String ip = "10.1.2.3"; event.setCoreIp(ip); final String type = "myType"; event.setCoreType(type); event.setEventDate(eventDateTime.getMillis()); final ArrayList<ThriftField> fields = new ArrayList<ThriftField>(); fields.add(ThriftField.createThriftField(coreHostname, (short) 15)); fields.add(ThriftField.createThriftField(ip, (short) 14)); fields.add(ThriftField.createThriftField(type, (short) 16)); fields.add(ThriftField.createThriftField(eventDateTime.getMillis(), (short) 1)); final ThriftEnvelope envelope = new ThriftEnvelope("TLoggingEvent", fields); final ThriftEnvelopeEvent envelopeEvent = new ThriftEnvelopeEvent(eventDateTime, envelope); final TLoggingEvent event2 = ThriftEnvelopeEventToThrift.extractThrift(TLoggingEvent.class, envelopeEvent); Assert.assertEquals(event2.getCoreHostname(), event.getCoreHostname()); Assert.assertEquals(event2.getCoreIp(), event.getCoreIp()); Assert.assertEquals(event2.getCoreType(), event.getCoreType()); Assert.assertEquals(event2.getEventDate(), event.getEventDate()); }
ThriftEnvelopeEvent implements Event { @Override public String getOutputDir(final String prefix) { final GranularityPathMapper pathMapper = new GranularityPathMapper(String.format("%s/%s", prefix, thriftEnvelope.getTypeName()), granularity); return pathMapper.getPathForDateTime(getEventDateTime()); } ThriftEnvelopeEvent(); ThriftEnvelopeEvent(final DateTime eventDateTime, final ThriftEnvelope thriftEnvelope); ThriftEnvelopeEvent(final DateTime eventDateTime, final ThriftEnvelope thriftEnvelope, final Granularity granularity); ThriftEnvelopeEvent(final InputStream in, final ThriftEnvelopeDeserializer deserializer); @Override DateTime getEventDateTime(); @Override String getName(); @Override Granularity getGranularity(); @Override String getVersion(); @Override String getOutputDir(final String prefix); @Override Object getData(); @Override byte[] getSerializedEvent(); @Override void readExternal(final ObjectInput in); @Override void writeExternal(final ObjectOutput out); @Override String toString(); }
@Test(groups = "fast") public void testGetOutputDir() throws Exception { final ThriftEnvelope thriftEnvelope = new ThriftEnvelope(eventType); thriftEnvelope.getPayload().add(ThriftField.createThriftField("fuuness", (short) 0)); thriftEnvelope.getPayload().add(ThriftField.createThriftField(100L, (short) 1)); final ThriftEnvelopeEvent event = new ThriftEnvelopeEvent(new DateTime("2009-01-01T02:03:04"), thriftEnvelope); Assert.assertEquals(event.getOutputDir("/events/ning"), String.format("/events/ning/%s/2009/01/01/02", eventType)); }
ThriftEnvelopeEvent implements Event { @Override public String getVersion() { return thriftEnvelope.getVersion(); } ThriftEnvelopeEvent(); ThriftEnvelopeEvent(final DateTime eventDateTime, final ThriftEnvelope thriftEnvelope); ThriftEnvelopeEvent(final DateTime eventDateTime, final ThriftEnvelope thriftEnvelope, final Granularity granularity); ThriftEnvelopeEvent(final InputStream in, final ThriftEnvelopeDeserializer deserializer); @Override DateTime getEventDateTime(); @Override String getName(); @Override Granularity getGranularity(); @Override String getVersion(); @Override String getOutputDir(final String prefix); @Override Object getData(); @Override byte[] getSerializedEvent(); @Override void readExternal(final ObjectInput in); @Override void writeExternal(final ObjectOutput out); @Override String toString(); }
@Test(groups = "fast") public void testVersion1() throws Exception { final ThriftEnvelope thriftEnvelope = new ThriftEnvelope(eventType); thriftEnvelope.getPayload().add(ThriftField.createThriftField(100L, (short) 4)); thriftEnvelope.getPayload().add(ThriftField.createThriftField("fuuness", (short) 1)); final ThriftEnvelopeEvent event = new ThriftEnvelopeEvent(new DateTime("2009-01-01T02:03:04"), thriftEnvelope); Assert.assertEquals(event.getVersion(), "1.4"); } @Test(groups = "fast") public void testVersion2() throws Exception { final ThriftEnvelope thriftEnvelope = new ThriftEnvelope(eventType); thriftEnvelope.getPayload().add(ThriftField.createThriftField("fuuness", (short) 1)); thriftEnvelope.getPayload().add(ThriftField.createThriftField(100L, (short) 4)); final ThriftEnvelopeEvent event = new ThriftEnvelopeEvent(new DateTime("2009-01-01T02:03:04"), thriftEnvelope); Assert.assertEquals(event.getVersion(), "1.4"); }
ThriftToThriftEnvelopeEvent { public static <T extends Serializable> ThriftEnvelopeEvent extractEvent(final String eventName, final T thriftObject) { return extractEvent(eventName, new DateTime(), thriftObject); } static ThriftEnvelopeEvent extractEvent(final String eventName, final T thriftObject); static ThriftEnvelopeEvent extractEvent(final String eventName, final DateTime eventDateTime, final T thriftObject); static ThriftEnvelopeEvent extractEvent(final String type, final byte[] payload); static ThriftEnvelopeEvent extractEvent(final String type, final DateTime eventDateTime, final byte[] payload); }
@Test public void testExtractEvent() throws Exception { final DateTime eventDateTime = new DateTime(); final String coreHostname = "hostname"; final TLoggingEvent event = new TLoggingEvent(); event.setCoreHostname(coreHostname); final String ip = "10.1.2.3"; event.setCoreIp(ip); final String type = "coic"; event.setCoreType(type); event.setEventDate(eventDateTime.getMillis()); final ThriftEnvelopeEvent envelopeEvent = ThriftToThriftEnvelopeEvent.extractEvent("TLoggingEvent", event); final TLoggingEvent finalEvent = ThriftEnvelopeEventToThrift.extractThrift(TLoggingEvent.class, envelopeEvent); Assert.assertEquals(finalEvent.getCoreHostname(), event.getCoreHostname()); Assert.assertEquals(finalEvent.getCoreHostname(), coreHostname); Assert.assertEquals(finalEvent.getCoreIp(), event.getCoreIp()); Assert.assertEquals(finalEvent.getCoreIp(), ip); Assert.assertEquals(finalEvent.getCoreType(), event.getCoreType()); Assert.assertEquals(finalEvent.getCoreType(), type); Assert.assertEquals(finalEvent.getEventDate(), event.getEventDate()); Assert.assertEquals(finalEvent.getEventDate(), eventDateTime.getMillis()); for (final ThriftField field : ((ThriftEnvelope) envelopeEvent.getData()).getPayload()) { Assert.assertTrue(field.getId() > 0); } }
ThresholdEventWriter implements EventWriter { @Managed(description = "Commit locally spooled events for flushing") @Override public synchronized void forceCommit() throws IOException { log.debug("Performing commit on delegate EventWriter [{}]", delegate.getClass()); delegate.commit(); uncommittedWriteCount = 0; lastCommitNanos = getNow(); } ThresholdEventWriter(final EventWriter delegate, final long maxUncommittedWriteCount, final long maxUncommittedPeriodInSeconds); @Override synchronized void write(final Event event); @Managed(description = "Commit locally spooled events for flushing") @Override synchronized void forceCommit(); @Override synchronized void commit(); @Override synchronized void rollback(); @Override synchronized void flush(); @Override synchronized void close(); @Override String getSpoolPath(); @Managed(description = "Set the max number of writes before a commit is performed") void setMaxWriteCount(final long maxWriteCount); @Managed(description = "The max number of writes before a commit is performed") long getMaxWriteCount(); @Managed(description = "Set the max number of seconds between commits of local disk spools") void setMaxUncommittedPeriodInSeconds(final long maxUncommittedPeriodInSeconds); @Managed(description = "The max number of seconds between commits of local disk spools") long getMaxUncommittedPeriodInSeconds(); }
@Test(groups = "fast") public void testForceCommit() throws Exception { writeAndTestCounts(1, 0); writeAndTestCounts(2, 0); eventWriter.forceCommit(); assertTestCounts(0, 2); }
ThresholdEventWriter implements EventWriter { @Override public synchronized void commit() throws IOException { commitIfNeeded(); } ThresholdEventWriter(final EventWriter delegate, final long maxUncommittedWriteCount, final long maxUncommittedPeriodInSeconds); @Override synchronized void write(final Event event); @Managed(description = "Commit locally spooled events for flushing") @Override synchronized void forceCommit(); @Override synchronized void commit(); @Override synchronized void rollback(); @Override synchronized void flush(); @Override synchronized void close(); @Override String getSpoolPath(); @Managed(description = "Set the max number of writes before a commit is performed") void setMaxWriteCount(final long maxWriteCount); @Managed(description = "The max number of writes before a commit is performed") long getMaxWriteCount(); @Managed(description = "Set the max number of seconds between commits of local disk spools") void setMaxUncommittedPeriodInSeconds(final long maxUncommittedPeriodInSeconds); @Managed(description = "The max number of seconds between commits of local disk spools") long getMaxUncommittedPeriodInSeconds(); }
@Test(groups = "fast") public void testCommit() throws Exception { writeAndTestCounts(1, 0); writeAndTestCounts(2, 0); eventWriter.commit(); assertTestCounts(2, 0); now = now.plusSeconds(301); eventWriter.commit(); assertTestCounts(0, 2); }
ThresholdEventWriter implements EventWriter { @Override public synchronized void write(final Event event) throws IOException { if (!acceptsEvents) { log.warn("Writer not ready, discarding event: {}", event); return; } delegate.write(event); uncommittedWriteCount++; commitIfNeeded(); } ThresholdEventWriter(final EventWriter delegate, final long maxUncommittedWriteCount, final long maxUncommittedPeriodInSeconds); @Override synchronized void write(final Event event); @Managed(description = "Commit locally spooled events for flushing") @Override synchronized void forceCommit(); @Override synchronized void commit(); @Override synchronized void rollback(); @Override synchronized void flush(); @Override synchronized void close(); @Override String getSpoolPath(); @Managed(description = "Set the max number of writes before a commit is performed") void setMaxWriteCount(final long maxWriteCount); @Managed(description = "The max number of writes before a commit is performed") long getMaxWriteCount(); @Managed(description = "Set the max number of seconds between commits of local disk spools") void setMaxUncommittedPeriodInSeconds(final long maxUncommittedPeriodInSeconds); @Managed(description = "The max number of seconds between commits of local disk spools") long getMaxUncommittedPeriodInSeconds(); }
@Test(groups = "fast") public void testWriteException() throws Exception { try { delegateWriter.setWriteThrowsException(true); eventWriter.write(event); Assert.fail("expected exception"); } catch (IOException e) { Assert.assertEquals(e.getClass(), IOException.class); } } @Test(groups = "fast") public void testCommitException() throws Exception { try { delegateWriter.setCommitThrowsException(true); now = now.plusSeconds(301); eventWriter.write(event); Assert.fail("expected exception"); } catch (IOException e) { Assert.assertEquals(e.getClass(), IOException.class); } }
ThresholdEventWriter implements EventWriter { @Override public synchronized void rollback() throws IOException { delegate.rollback(); } ThresholdEventWriter(final EventWriter delegate, final long maxUncommittedWriteCount, final long maxUncommittedPeriodInSeconds); @Override synchronized void write(final Event event); @Managed(description = "Commit locally spooled events for flushing") @Override synchronized void forceCommit(); @Override synchronized void commit(); @Override synchronized void rollback(); @Override synchronized void flush(); @Override synchronized void close(); @Override String getSpoolPath(); @Managed(description = "Set the max number of writes before a commit is performed") void setMaxWriteCount(final long maxWriteCount); @Managed(description = "The max number of writes before a commit is performed") long getMaxWriteCount(); @Managed(description = "Set the max number of seconds between commits of local disk spools") void setMaxUncommittedPeriodInSeconds(final long maxUncommittedPeriodInSeconds); @Managed(description = "The max number of seconds between commits of local disk spools") long getMaxUncommittedPeriodInSeconds(); }
@Test(groups = "fast") public void testRollbackException() throws Exception { try { delegateWriter.setRollbackThrowsException(true); eventWriter.rollback(); Assert.fail("expected exception"); } catch (IOException e) { Assert.assertEquals(e.getClass(), IOException.class); } }
IntegerDataItem implements DataItem { @Override public Short getShort() { return value.shortValue(); } IntegerDataItem(); IntegerDataItem(final int value); @Override Boolean getBoolean(); @Override Byte getByte(); @Override Integer getInteger(); @Override Short getShort(); @Override Long getLong(); @Override String getString(); @Override Double getDouble(); @Override Comparable getComparable(); @Override int compareTo(final Object o); @Override boolean equals(final Object o); @Override int hashCode(); @Override void write(final DataOutput out); @Override void readFields(final DataInput in); @Override String toString(); @Override byte getThriftType(); }
@Test(groups = "fast") public void testConvertToShort() throws Exception { Assert.assertEquals(value0.getShort(), Short.valueOf((short) 0)); Assert.assertEquals(value1.getShort(), Short.valueOf((short) 1)); Assert.assertEquals(value1000000.getShort(), Short.valueOf((short) 16960)); Assert.assertEquals(valueMinus1000000.getShort(), Short.valueOf((short) -16960)); }
DiskSpoolEventWriter implements EventWriter { @Override public synchronized void write(final Event event) throws IOException { if (!acceptsEvents) { log.warn("Writer not ready, discarding event: {}", event); return; } if (currentOutputter == null) { currentOutputFile = new File(tmpSpoolDirectory, String.format("%d.bin", fileId.incrementAndGet())); final FileOutputStream outputStream = codec.getFileOutputStream(currentOutputFile); if (eventSerializer == null) { currentOutputter = ObjectOutputterFactory.createObjectOutputter(outputStream, syncType, syncBatchSize); } else { currentOutputter = ObjectOutputterFactory.createObjectOutputter(outputStream, syncType, syncBatchSize, eventSerializer); } } try { final long startTime = System.nanoTime(); currentOutputter.writeObject(event); writeTimer.update(System.nanoTime() - startTime, TimeUnit.NANOSECONDS); } catch (RuntimeException e) { eventSerializationFailures.incrementAndGet(); throw new IOException("unable to serialize event", e); } catch (IOException e) { eventSerializationFailures.incrementAndGet(); try { forceCommit(); } catch (IOException ignored) { } throw new IOException("unable to serialize event", e); } } DiskSpoolEventWriter( final EventHandler eventHandler, final String spoolPath, final boolean flushEnabled, final long flushIntervalInSeconds, final ScheduledExecutorService executor, final SyncType syncType, final int syncBatchSize ); DiskSpoolEventWriter( final EventHandler eventHandler, final String spoolPath, final boolean flushEnabled, final long flushIntervalInSeconds, final ScheduledExecutorService executor, final SyncType syncType, final int syncBatchSize, final CompressionCodec codec, final EventSerializer eventSerializer ); @Override synchronized void write(final Event event); @Override synchronized void commit(); @Override synchronized void forceCommit(); @Override synchronized void rollback(); @Override synchronized void close(); @Override String getSpoolPath(); @Managed(description = "Flush events (forward them to final handler)") void flush(); @Managed(description = "enable/disable flushing to hdfs") void setFlushEnabled(final boolean enabled); @Managed(description = "check if hdfs flushing is enabled") boolean getFlushEnabled(); @Managed(description = "set the commit interval for next scheduled commit to hdfs in seconds") void setFlushIntervalInSeconds(final long seconds); @Managed(description = "get the current commit interval to hdfs in seconds") long getFlushIntervalInSeconds(); @Managed(description = "size in kilobytes of disk spool queue not yet written to hdfs") long getDiskSpoolSize(); @Managed(description = "size in kilobytes of quarantined data that could not be written to hdfs") long getQuarantineSize(); @Managed(description = "attempt to process quarantined files") synchronized void processQuarantinedFiles(); @Managed(description = "count of events that could not be serialized from memory to disk") long getEventSeralizationFailureCount(); }
@Test(groups = "fast") public void testWriteIOFailure() throws Exception { final DiskSpoolEventWriter writer = createWriter(writerSucceeds); try { writer.write(eventThrowsOnWrite); Assert.fail("expected IOException"); } catch (IOException e) { Assert.assertEquals(e.getClass(), IOException.class); } testSpoolDirs(0, 1, 0); }
IntegerDataItem implements DataItem { @Override public Long getLong() { return value.longValue(); } IntegerDataItem(); IntegerDataItem(final int value); @Override Boolean getBoolean(); @Override Byte getByte(); @Override Integer getInteger(); @Override Short getShort(); @Override Long getLong(); @Override String getString(); @Override Double getDouble(); @Override Comparable getComparable(); @Override int compareTo(final Object o); @Override boolean equals(final Object o); @Override int hashCode(); @Override void write(final DataOutput out); @Override void readFields(final DataInput in); @Override String toString(); @Override byte getThriftType(); }
@Test(groups = "fast") public void testConvertToLong() throws Exception { Assert.assertEquals(value0.getLong(), Long.valueOf(0)); Assert.assertEquals(value1.getLong(), Long.valueOf(1)); Assert.assertEquals(value1000000.getLong(), Long.valueOf(1000000)); Assert.assertEquals(valueMinus1000000.getLong(), Long.valueOf(-1000000)); }
EventHubCollector extends CollectorComponent { @Override public EventHubCollector start() { if (!closed.get()) lazyRegisterEventProcessorFactoryWithHost.get(); return this; } EventHubCollector(Builder builder); EventHubCollector( LazyRegisterEventProcessorFactoryWithHost lazyRegisterEventProcessorFactoryWithHost); static Builder newBuilder(); @Override EventHubCollector start(); @Override CheckResult check(); @Override void close(); }
@Test public void start_invokesRegistration() { EventHubCollector collector = new EventHubCollector(new LazyFuture()); collector.start(); assertThat(registration).isCompleted(); } @Test public void start_registersOnlyOnce() { AtomicInteger registrations = new AtomicInteger(); EventHubCollector collector = new EventHubCollector( new LazyFuture() { @Override protected Future<?> compute() { registrations.incrementAndGet(); return super.compute(); } }); collector.start(); collector.start(); assertThat(registrations.get()).isEqualTo(1); }
ZipkinEventProcessor implements IEventProcessor { @Override public void onEvents(PartitionContext context, Iterable<EventData> messages) throws ExecutionException, InterruptedException { List<Span> buffer = new ArrayList<>(); for (EventData data : messages) { byte[] bytes = data.getBytes(); BytesDecoder<Span> decoder = decoderForListMessage(bytes); List<Span> nextSpans = decoder.decodeList(bytes); buffer.addAll(nextSpans); if (maybeCheckpoint(context, data, nextSpans.size())) { collector.accept(buffer, NOOP); buffer.clear(); } } if (!buffer.isEmpty()) { collector.accept(buffer, NOOP); } } ZipkinEventProcessor(Collector collector, int checkpointBatchSize); ZipkinEventProcessor(Logger logger, Collector collector, int checkpointBatchSize); @Override void onOpen(PartitionContext context); @Override void onClose(PartitionContext context, CloseReason reason); @Override void onEvents(PartitionContext context, Iterable<EventData> messages); @Override void onError(PartitionContext context, Throwable error); }
@Test public void parallelCheckpoint() throws Exception { int spansPerEvent = 3; int eventsPerCheckpoint = processor.checkpointBatchSize / spansPerEvent; if (processor.checkpointBatchSize % spansPerEvent > 0) eventsPerCheckpoint++; int eventCount = 1000; final ConcurrentLinkedQueue<EventData> events = new ConcurrentLinkedQueue<>(); for (int i = 0; i < eventCount; i++) { events.add(jsonMessageWithThreeSpans(Integer.toHexString(i + 1), 1 + i)); } CountDownLatch latch = new CountDownLatch(events.size()); int threadCount = 10; ExecutorService exec = Executors.newFixedThreadPool(threadCount); for (int i = 0; i < threadCount; i++) { exec.execute( () -> { EventData event; while ((event = events.poll()) != null) { try { processor.onEvents(context, asList(event)); } catch (Exception e) { e.printStackTrace(); } latch.countDown(); } }); } exec.shutdown(); exec.awaitTermination(1, TimeUnit.SECONDS); assertThat(processor.countSinceCheckpoint).isZero(); assertThat(checkpointEvents).hasSize(eventCount / eventsPerCheckpoint); } @Test public void checkpointsOnBatchSize() throws Exception { EventData event1 = jsonMessageWithThreeSpans("a", 1); EventData event2 = json2MessageWithThreeSpans("b", 2); EventData event3 = thriftMessageWithThreeSpans("c", 3); EventData event4 = json2MessageWithThreeSpans("d", 4); processor.onEvents(context, asList(event1, event2, event3)); assertThat(checkpointEvents).isEmpty(); assertThat(logger.messages.poll()).isNull(); processor.onEvents(context, asList(event4)); assertThat(checkpointEvents).containsExactly(event4); assertThat(logger.messages.poll()).isEqualTo("FINE: Partition 1 checkpointing at d,4"); }
EventHubCollector extends CollectorComponent { @Override public CheckResult check() { try { Future<?> registrationFuture = lazyRegisterEventProcessorFactoryWithHost.get(); registrationFuture.get(); return CheckResult.OK; } catch (RuntimeException e) { return CheckResult.failed(e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return CheckResult.failed(e); } catch (ExecutionException e) { Throwable cause = e.getCause(); if (cause instanceof Error) throw (Error) cause; return CheckResult.failed(cause); } } EventHubCollector(Builder builder); EventHubCollector( LazyRegisterEventProcessorFactoryWithHost lazyRegisterEventProcessorFactoryWithHost); static Builder newBuilder(); @Override EventHubCollector start(); @Override CheckResult check(); @Override void close(); }
@Test public void check_invokesRegistration() { EventHubCollector collector = new EventHubCollector(new LazyFuture()); assertThat(collector.check().ok()).isTrue(); assertThat(registration).isCompleted(); } @Test public void check_failsOnRuntimeException_registering() { RuntimeException exception = new RuntimeException(); EventHubCollector collector = new EventHubCollector( new LazyFuture() { @Override protected Future<?> compute() { throw exception; } }); CheckResult result = collector.check(); assertThat(result.error()).isEqualTo(exception); } @Test public void check_failsOnRuntimeException_registration() { RuntimeException exception = new RuntimeException(); EventHubCollector collector = new EventHubCollector( new LazyFuture() { @Override protected Future<?> compute() { registration.completeExceptionally(exception); return registration; } }); CheckResult result = collector.check(); assertThat(result.error()).isEqualTo(exception); }
EventHubCollector extends CollectorComponent { public static Builder newBuilder() { return new Builder(); } EventHubCollector(Builder builder); EventHubCollector( LazyRegisterEventProcessorFactoryWithHost lazyRegisterEventProcessorFactoryWithHost); static Builder newBuilder(); @Override EventHubCollector start(); @Override CheckResult check(); @Override void close(); }
@Test public void blobpathprefix_set_toaconstant_atstartup() { EventHubCollector.Builder builder1 = EventHubCollector.newBuilder(); EventHubCollector.Builder builder2 = EventHubCollector.newBuilder(); assertThat(builder2.storageBlobPrefix).isEqualTo(builder1.storageBlobPrefix); }
LazyRegisterEventProcessorFactoryWithHost { Future<?> get() { if (future == null) { synchronized (this) { if (future == null) { future = compute(); } } } return future; } LazyRegisterEventProcessorFactoryWithHost(EventHubCollector.Builder builder); }
@Test public void get_registersFactory() throws Exception { LazyRegisterEventProcessorFactoryWithHost lazy = new TestLazyRegisterEventProcessorFactoryWithHost(); lazy.get(); assertThat(registration).isCompleted(); } @Test public void get_doesntWrapRuntimeException() throws Exception { RuntimeException exception = new RuntimeException("Failure initializing Storage lease manager"); LazyRegisterEventProcessorFactoryWithHost lazy = new TestLazyRegisterEventProcessorFactoryWithHost() { @Override Future<?> registerEventProcessorFactoryWithHost() throws Exception { throw exception; } }; thrown.expect(is(exception)); lazy.get(); } @Test public void get_wrapsCheckedException() throws Exception { LazyRegisterEventProcessorFactoryWithHost lazy = new TestLazyRegisterEventProcessorFactoryWithHost() { @Override Future<?> registerEventProcessorFactoryWithHost() throws InvalidKeyException { throw new InvalidKeyException(); } }; thrown.expect(RuntimeException.class); thrown.expectCause(isA(InvalidKeyException.class)); lazy.get(); }
RxFirebaseAuth { @CheckResult @NonNull public static Observable<FirebaseAuth> authStateChanges( @NonNull FirebaseAuth instance) { return Observable.create(new AuthStateChangesOnSubscribe(instance)); } private RxFirebaseAuth(); @CheckResult @NonNull static Observable<FirebaseAuth> authStateChanges( @NonNull FirebaseAuth instance); @CheckResult @NonNull static Single<FirebaseUser> createUserWithEmailAndPassword( @NonNull FirebaseAuth instance, @NonNull String email, @NonNull String password); @CheckResult @NonNull static Maybe<List<String>> fetchProvidersForEmail( @NonNull FirebaseAuth instance, @NonNull String email); @CheckResult @NonNull static Maybe<FirebaseUser> getCurrentUser( @NonNull final FirebaseAuth instance); @CheckResult @NonNull static Completable sendPasswordResetEmail( @NonNull FirebaseAuth instance, @NonNull String email); @CheckResult @NonNull static Single<FirebaseUser> signInAnonymously( @NonNull FirebaseAuth instance); @CheckResult @NonNull static Single<FirebaseUser> signInWithCredential( @NonNull FirebaseAuth instance, @NonNull AuthCredential credential); @CheckResult @NonNull static Single<FirebaseUser> signInWithCustomToken( @NonNull FirebaseAuth instance, @NonNull String token); @CheckResult @NonNull static Single<FirebaseUser> signInWithEmailAndPassword( @NonNull FirebaseAuth instance, @NonNull String email, @NonNull String password); @CheckResult @NonNull static Completable signOut(@NonNull FirebaseAuth instance); @CheckResult @NonNull static Completable applyActionCode(@NonNull FirebaseAuth instance, @NonNull String code); @CheckResult @NonNull static Single<ActionCodeResult> checkActionCode( @NonNull FirebaseAuth instance, @NonNull String code); @CheckResult @NonNull static Completable confirmPasswordReset( @NonNull FirebaseAuth instance, @NonNull String code, @NonNull String newPassword); @CheckResult @NonNull static Single<String> verifyPasswordResetCode( @NonNull FirebaseAuth instance, @NonNull String code); }
@Test public void testAuthStateChanges() { TestObserver<FirebaseAuth> obs = TestObserver.create(); RxFirebaseAuth.authStateChanges(mockFirebaseAuth).subscribe(obs); callOnAuthStateChanged(); obs.assertNotComplete(); obs.assertValueCount(1); obs.dispose(); callOnAuthStateChanged(); obs.assertValueCount(1); }
RxFirebaseDatabase { @NonNull @CheckResult public static Completable setPriority(@NonNull DatabaseReference ref, @NonNull Object priority) { return Completable.create(new SetPriorityOnSubscribe(ref, priority)); } private RxFirebaseDatabase(); @NonNull @CheckResult static Observable<ChildEvent> childEvents( @NonNull DatabaseReference ref); @NonNull @CheckResult static Single<DataSnapshot> data(@NonNull DatabaseReference ref); @NonNull @CheckResult static Observable<DataSnapshot> dataChanges( @NonNull DatabaseReference ref); @NonNull @CheckResult static Observable<Optional<T>> dataChangesOf( @NonNull DatabaseReference ref, @NonNull Class<T> clazz); @NonNull @CheckResult static Observable<Optional<T>> dataChangesOf( @NonNull DatabaseReference ref, @NonNull GenericTypeIndicator<T> typeIndicator); @NonNull @CheckResult static Single<Optional<T>> dataOf(@NonNull DatabaseReference ref, @NonNull Class<T> clazz); @NonNull @CheckResult static Single<Optional<T>> dataOf(@NonNull DatabaseReference ref, @NonNull GenericTypeIndicator<T> typeIndicator); @NonNull @CheckResult static Completable removeValue(@NonNull DatabaseReference ref); @NonNull @CheckResult static Completable setPriority(@NonNull DatabaseReference ref, @NonNull Object priority); @NonNull @CheckResult static Completable setValue(@NonNull DatabaseReference ref, @Nullable T value); @NonNull @CheckResult static Completable setValue(@NonNull DatabaseReference ref, @Nullable T value, @NonNull Object priority); @NonNull @CheckResult static Completable runTransaction(@NonNull DatabaseReference ref, @NonNull Function<MutableData, Transaction.Result> task); @NonNull @CheckResult static Completable runTransaction(@NonNull DatabaseReference ref, boolean fireLocalEvents, @NonNull Function<MutableData, Transaction.Result> task); @NonNull @CheckResult static Completable updateChildren(@NonNull DatabaseReference ref, @NonNull Map<String, Object> update); }
@Test public void testSetPriority() { when(mockDatabaseReference.setPriority(1)).thenReturn(mockTask); TestObserver sub = TestObserver.create(); RxFirebaseDatabase.setPriority(mockDatabaseReference, 1).subscribe(sub); verifyAddOnCompleteListenerForTask(); callTaskOnComplete(); sub.assertComplete(); sub.assertNoErrors(); sub.dispose(); } @Test public void testSetPriority_notSuccessful() { when(mockDatabaseReference.setPriority(1)).thenReturn(mockTask); TestObserver sub = TestObserver.create(); RxFirebaseDatabase.setPriority(mockDatabaseReference, 1).subscribe(sub); verifyAddOnCompleteListenerForTask(); callTaskOnCompleteWithError(new IllegalStateException()); sub.assertNotComplete(); sub.assertError(IllegalStateException.class); }
RxFirebaseDatabase { @NonNull @CheckResult public static <T> Completable setValue(@NonNull DatabaseReference ref, @Nullable T value) { return Completable.create(new SetValueOnSubscribe<T>(ref, value)); } private RxFirebaseDatabase(); @NonNull @CheckResult static Observable<ChildEvent> childEvents( @NonNull DatabaseReference ref); @NonNull @CheckResult static Single<DataSnapshot> data(@NonNull DatabaseReference ref); @NonNull @CheckResult static Observable<DataSnapshot> dataChanges( @NonNull DatabaseReference ref); @NonNull @CheckResult static Observable<Optional<T>> dataChangesOf( @NonNull DatabaseReference ref, @NonNull Class<T> clazz); @NonNull @CheckResult static Observable<Optional<T>> dataChangesOf( @NonNull DatabaseReference ref, @NonNull GenericTypeIndicator<T> typeIndicator); @NonNull @CheckResult static Single<Optional<T>> dataOf(@NonNull DatabaseReference ref, @NonNull Class<T> clazz); @NonNull @CheckResult static Single<Optional<T>> dataOf(@NonNull DatabaseReference ref, @NonNull GenericTypeIndicator<T> typeIndicator); @NonNull @CheckResult static Completable removeValue(@NonNull DatabaseReference ref); @NonNull @CheckResult static Completable setPriority(@NonNull DatabaseReference ref, @NonNull Object priority); @NonNull @CheckResult static Completable setValue(@NonNull DatabaseReference ref, @Nullable T value); @NonNull @CheckResult static Completable setValue(@NonNull DatabaseReference ref, @Nullable T value, @NonNull Object priority); @NonNull @CheckResult static Completable runTransaction(@NonNull DatabaseReference ref, @NonNull Function<MutableData, Transaction.Result> task); @NonNull @CheckResult static Completable runTransaction(@NonNull DatabaseReference ref, boolean fireLocalEvents, @NonNull Function<MutableData, Transaction.Result> task); @NonNull @CheckResult static Completable updateChildren(@NonNull DatabaseReference ref, @NonNull Map<String, Object> update); }
@Test public void testSetValue() { when(mockDatabaseReference.setValue(1)).thenReturn(mockTask); TestObserver sub = TestObserver.create(); RxFirebaseDatabase.setValue(mockDatabaseReference, 1).subscribe(sub); verifyAddOnCompleteListenerForTask(); callTaskOnComplete(); sub.assertComplete(); sub.assertNoErrors(); sub.dispose(); } @Test public void testSetValue_notSuccessful() { when(mockDatabaseReference.setValue(1)).thenReturn(mockTask); TestObserver sub = TestObserver.create(); RxFirebaseDatabase.setValue(mockDatabaseReference, 1).subscribe(sub); verifyAddOnCompleteListenerForTask(); callTaskOnCompleteWithError(new IllegalStateException()); sub.assertNotComplete(); sub.assertError(IllegalStateException.class); } @Test public void testSetValueWithPriority() { when(mockDatabaseReference.setValue(1, 1)).thenReturn(mockTask); TestObserver sub = TestObserver.create(); RxFirebaseDatabase.setValue(mockDatabaseReference, 1, 1).subscribe(sub); verifyAddOnCompleteListenerForTask(); callTaskOnComplete(); sub.assertComplete(); sub.assertNoErrors(); sub.dispose(); } @Test public void testSetValueWithPriority_notSuccessful() { when(mockDatabaseReference.setValue(1, 1)).thenReturn(mockTask); TestObserver sub = TestObserver.create(); RxFirebaseDatabase.setValue(mockDatabaseReference, 1, 1).subscribe(sub); verifyAddOnCompleteListenerForTask(); callTaskOnCompleteWithError(new IllegalStateException()); sub.assertNotComplete(); sub.assertError(IllegalStateException.class); sub.dispose(); }
RxFirebaseDatabase { @NonNull @CheckResult public static Completable updateChildren(@NonNull DatabaseReference ref, @NonNull Map<String, Object> update) { return Completable.create(new UpdateChildrenOnSubscribe(ref, update)); } private RxFirebaseDatabase(); @NonNull @CheckResult static Observable<ChildEvent> childEvents( @NonNull DatabaseReference ref); @NonNull @CheckResult static Single<DataSnapshot> data(@NonNull DatabaseReference ref); @NonNull @CheckResult static Observable<DataSnapshot> dataChanges( @NonNull DatabaseReference ref); @NonNull @CheckResult static Observable<Optional<T>> dataChangesOf( @NonNull DatabaseReference ref, @NonNull Class<T> clazz); @NonNull @CheckResult static Observable<Optional<T>> dataChangesOf( @NonNull DatabaseReference ref, @NonNull GenericTypeIndicator<T> typeIndicator); @NonNull @CheckResult static Single<Optional<T>> dataOf(@NonNull DatabaseReference ref, @NonNull Class<T> clazz); @NonNull @CheckResult static Single<Optional<T>> dataOf(@NonNull DatabaseReference ref, @NonNull GenericTypeIndicator<T> typeIndicator); @NonNull @CheckResult static Completable removeValue(@NonNull DatabaseReference ref); @NonNull @CheckResult static Completable setPriority(@NonNull DatabaseReference ref, @NonNull Object priority); @NonNull @CheckResult static Completable setValue(@NonNull DatabaseReference ref, @Nullable T value); @NonNull @CheckResult static Completable setValue(@NonNull DatabaseReference ref, @Nullable T value, @NonNull Object priority); @NonNull @CheckResult static Completable runTransaction(@NonNull DatabaseReference ref, @NonNull Function<MutableData, Transaction.Result> task); @NonNull @CheckResult static Completable runTransaction(@NonNull DatabaseReference ref, boolean fireLocalEvents, @NonNull Function<MutableData, Transaction.Result> task); @NonNull @CheckResult static Completable updateChildren(@NonNull DatabaseReference ref, @NonNull Map<String, Object> update); }
@Test public void testUpdateChildren() { Map<String, Object> map = new HashMap<>(); when(mockDatabaseReference.updateChildren(map)).thenReturn(mockTask); TestObserver sub = TestObserver.create(); RxFirebaseDatabase.updateChildren(mockDatabaseReference, map).subscribe(sub); verifyAddOnCompleteListenerForTask(); callTaskOnComplete(); sub.assertComplete(); sub.assertNoErrors(); sub.dispose(); } @Test public void testUpdateChildren_notSuccessful() { Map<String, Object> map = new HashMap<>(); when(mockDatabaseReference.updateChildren(map)).thenReturn(mockTask); TestObserver sub = TestObserver.create(); RxFirebaseDatabase.updateChildren(mockDatabaseReference, map).subscribe(sub); verifyAddOnCompleteListenerForTask(); callTaskOnCompleteWithError(new IllegalStateException()); sub.assertNotComplete(); sub.assertError(IllegalStateException.class); sub.dispose(); }
RxFirebaseDatabase { @NonNull @CheckResult public static Completable runTransaction(@NonNull DatabaseReference ref, @NonNull Function<MutableData, Transaction.Result> task) { return runTransaction(ref, true, task); } private RxFirebaseDatabase(); @NonNull @CheckResult static Observable<ChildEvent> childEvents( @NonNull DatabaseReference ref); @NonNull @CheckResult static Single<DataSnapshot> data(@NonNull DatabaseReference ref); @NonNull @CheckResult static Observable<DataSnapshot> dataChanges( @NonNull DatabaseReference ref); @NonNull @CheckResult static Observable<Optional<T>> dataChangesOf( @NonNull DatabaseReference ref, @NonNull Class<T> clazz); @NonNull @CheckResult static Observable<Optional<T>> dataChangesOf( @NonNull DatabaseReference ref, @NonNull GenericTypeIndicator<T> typeIndicator); @NonNull @CheckResult static Single<Optional<T>> dataOf(@NonNull DatabaseReference ref, @NonNull Class<T> clazz); @NonNull @CheckResult static Single<Optional<T>> dataOf(@NonNull DatabaseReference ref, @NonNull GenericTypeIndicator<T> typeIndicator); @NonNull @CheckResult static Completable removeValue(@NonNull DatabaseReference ref); @NonNull @CheckResult static Completable setPriority(@NonNull DatabaseReference ref, @NonNull Object priority); @NonNull @CheckResult static Completable setValue(@NonNull DatabaseReference ref, @Nullable T value); @NonNull @CheckResult static Completable setValue(@NonNull DatabaseReference ref, @Nullable T value, @NonNull Object priority); @NonNull @CheckResult static Completable runTransaction(@NonNull DatabaseReference ref, @NonNull Function<MutableData, Transaction.Result> task); @NonNull @CheckResult static Completable runTransaction(@NonNull DatabaseReference ref, boolean fireLocalEvents, @NonNull Function<MutableData, Transaction.Result> task); @NonNull @CheckResult static Completable updateChildren(@NonNull DatabaseReference ref, @NonNull Map<String, Object> update); }
@Test public void testRunTransaction() throws Exception { TestObserver sub = TestObserver.create(); RxFirebaseDatabase.runTransaction(mockDatabaseReference, mockTransactionTask).subscribe(sub); verifyRunTransaction(); callTransactionOnComplete(); verifyTransactionTaskCall(); sub.assertComplete(); sub.assertNoErrors(); sub.dispose(); } @Test public void testRunTransaction_onError() { TestObserver sub = TestObserver.create(); RxFirebaseDatabase.runTransaction(mockDatabaseReference, mockTransactionTask).subscribe(sub); verifyRunTransaction(); callTransactionOnCompleteWithError(new DatabaseException("Foo")); sub.assertNotComplete(); sub.assertError(DatabaseException.class); sub.dispose(); }
RxFirebaseAuth { @CheckResult @NonNull public static Single<FirebaseUser> signInAnonymously( @NonNull FirebaseAuth instance) { return Single.create(new SignInAnonymouslyOnSubscribe(instance)); } private RxFirebaseAuth(); @CheckResult @NonNull static Observable<FirebaseAuth> authStateChanges( @NonNull FirebaseAuth instance); @CheckResult @NonNull static Single<FirebaseUser> createUserWithEmailAndPassword( @NonNull FirebaseAuth instance, @NonNull String email, @NonNull String password); @CheckResult @NonNull static Maybe<List<String>> fetchProvidersForEmail( @NonNull FirebaseAuth instance, @NonNull String email); @CheckResult @NonNull static Maybe<FirebaseUser> getCurrentUser( @NonNull final FirebaseAuth instance); @CheckResult @NonNull static Completable sendPasswordResetEmail( @NonNull FirebaseAuth instance, @NonNull String email); @CheckResult @NonNull static Single<FirebaseUser> signInAnonymously( @NonNull FirebaseAuth instance); @CheckResult @NonNull static Single<FirebaseUser> signInWithCredential( @NonNull FirebaseAuth instance, @NonNull AuthCredential credential); @CheckResult @NonNull static Single<FirebaseUser> signInWithCustomToken( @NonNull FirebaseAuth instance, @NonNull String token); @CheckResult @NonNull static Single<FirebaseUser> signInWithEmailAndPassword( @NonNull FirebaseAuth instance, @NonNull String email, @NonNull String password); @CheckResult @NonNull static Completable signOut(@NonNull FirebaseAuth instance); @CheckResult @NonNull static Completable applyActionCode(@NonNull FirebaseAuth instance, @NonNull String code); @CheckResult @NonNull static Single<ActionCodeResult> checkActionCode( @NonNull FirebaseAuth instance, @NonNull String code); @CheckResult @NonNull static Completable confirmPasswordReset( @NonNull FirebaseAuth instance, @NonNull String code, @NonNull String newPassword); @CheckResult @NonNull static Single<String> verifyPasswordResetCode( @NonNull FirebaseAuth instance, @NonNull String code); }
@Test public void testSignInAnonymous_NotSuccessful() { mockNotSuccessfulAuthResult(new IllegalStateException()); when(mockFirebaseAuth.signInAnonymously()).thenReturn(mockAuthResultTask); TestObserver<FirebaseUser> obs = TestObserver.create(); RxFirebaseAuth.signInAnonymously(mockFirebaseAuth).subscribe(obs); callOnComplete(mockAuthResultTask); obs.dispose(); callOnComplete(mockAuthResultTask); obs.assertError(IllegalStateException.class); obs.assertNoValues(); } @Test public void testSignInAnonymous() { when(mockFirebaseUser.isAnonymous()).thenReturn(true); mockSuccessfulAuthResult(); when(mockFirebaseAuth.signInAnonymously()).thenReturn(mockAuthResultTask); TestObserver<FirebaseUser> obs = TestObserver.create(); RxFirebaseAuth.signInAnonymously(mockFirebaseAuth).subscribe(obs); callOnComplete(mockAuthResultTask); obs.dispose(); callOnComplete(mockAuthResultTask); obs.assertNoErrors(); obs.assertValue(new Predicate<FirebaseUser>() { @Override public boolean test(FirebaseUser firebaseUser) throws Exception { return firebaseUser.isAnonymous(); } }); }
RxFirebaseAuth { @CheckResult @NonNull public static Single<FirebaseUser> signInWithCredential( @NonNull FirebaseAuth instance, @NonNull AuthCredential credential) { return Single.create(new SignInWithCredentialOnSubscribe(instance, credential)); } private RxFirebaseAuth(); @CheckResult @NonNull static Observable<FirebaseAuth> authStateChanges( @NonNull FirebaseAuth instance); @CheckResult @NonNull static Single<FirebaseUser> createUserWithEmailAndPassword( @NonNull FirebaseAuth instance, @NonNull String email, @NonNull String password); @CheckResult @NonNull static Maybe<List<String>> fetchProvidersForEmail( @NonNull FirebaseAuth instance, @NonNull String email); @CheckResult @NonNull static Maybe<FirebaseUser> getCurrentUser( @NonNull final FirebaseAuth instance); @CheckResult @NonNull static Completable sendPasswordResetEmail( @NonNull FirebaseAuth instance, @NonNull String email); @CheckResult @NonNull static Single<FirebaseUser> signInAnonymously( @NonNull FirebaseAuth instance); @CheckResult @NonNull static Single<FirebaseUser> signInWithCredential( @NonNull FirebaseAuth instance, @NonNull AuthCredential credential); @CheckResult @NonNull static Single<FirebaseUser> signInWithCustomToken( @NonNull FirebaseAuth instance, @NonNull String token); @CheckResult @NonNull static Single<FirebaseUser> signInWithEmailAndPassword( @NonNull FirebaseAuth instance, @NonNull String email, @NonNull String password); @CheckResult @NonNull static Completable signOut(@NonNull FirebaseAuth instance); @CheckResult @NonNull static Completable applyActionCode(@NonNull FirebaseAuth instance, @NonNull String code); @CheckResult @NonNull static Single<ActionCodeResult> checkActionCode( @NonNull FirebaseAuth instance, @NonNull String code); @CheckResult @NonNull static Completable confirmPasswordReset( @NonNull FirebaseAuth instance, @NonNull String code, @NonNull String newPassword); @CheckResult @NonNull static Single<String> verifyPasswordResetCode( @NonNull FirebaseAuth instance, @NonNull String code); }
@Test public void testSignInWithCredential() { mockSuccessfulAuthResult(); when(mockFirebaseAuth.signInWithCredential(mockAuthCredential)).thenReturn(mockAuthResultTask); TestObserver<FirebaseUser> obs = TestObserver.create(); RxFirebaseAuth.signInWithCredential(mockFirebaseAuth, mockAuthCredential).subscribe(obs); callOnComplete(mockAuthResultTask); obs.dispose(); callOnComplete(mockAuthResultTask); obs.assertNoErrors(); obs.assertComplete(); obs.assertValueCount(1); } @Test public void testSignInWithCredential_NotSuccessful() { mockNotSuccessfulAuthResult(new IllegalStateException()); when(mockFirebaseAuth.signInWithCredential(mockAuthCredential)).thenReturn(mockAuthResultTask); TestObserver<FirebaseUser> obs = TestObserver.create(); RxFirebaseAuth.signInWithCredential(mockFirebaseAuth, mockAuthCredential).subscribe(obs); callOnComplete(mockAuthResultTask); obs.dispose(); callOnComplete(mockAuthResultTask); obs.assertError(IllegalStateException.class); obs.assertNoValues(); }
RxFirebaseAuth { @CheckResult @NonNull public static Single<FirebaseUser> signInWithCustomToken( @NonNull FirebaseAuth instance, @NonNull String token) { return Single.create(new SignInWithCustomTokenOnSubscribe(instance, token)); } private RxFirebaseAuth(); @CheckResult @NonNull static Observable<FirebaseAuth> authStateChanges( @NonNull FirebaseAuth instance); @CheckResult @NonNull static Single<FirebaseUser> createUserWithEmailAndPassword( @NonNull FirebaseAuth instance, @NonNull String email, @NonNull String password); @CheckResult @NonNull static Maybe<List<String>> fetchProvidersForEmail( @NonNull FirebaseAuth instance, @NonNull String email); @CheckResult @NonNull static Maybe<FirebaseUser> getCurrentUser( @NonNull final FirebaseAuth instance); @CheckResult @NonNull static Completable sendPasswordResetEmail( @NonNull FirebaseAuth instance, @NonNull String email); @CheckResult @NonNull static Single<FirebaseUser> signInAnonymously( @NonNull FirebaseAuth instance); @CheckResult @NonNull static Single<FirebaseUser> signInWithCredential( @NonNull FirebaseAuth instance, @NonNull AuthCredential credential); @CheckResult @NonNull static Single<FirebaseUser> signInWithCustomToken( @NonNull FirebaseAuth instance, @NonNull String token); @CheckResult @NonNull static Single<FirebaseUser> signInWithEmailAndPassword( @NonNull FirebaseAuth instance, @NonNull String email, @NonNull String password); @CheckResult @NonNull static Completable signOut(@NonNull FirebaseAuth instance); @CheckResult @NonNull static Completable applyActionCode(@NonNull FirebaseAuth instance, @NonNull String code); @CheckResult @NonNull static Single<ActionCodeResult> checkActionCode( @NonNull FirebaseAuth instance, @NonNull String code); @CheckResult @NonNull static Completable confirmPasswordReset( @NonNull FirebaseAuth instance, @NonNull String code, @NonNull String newPassword); @CheckResult @NonNull static Single<String> verifyPasswordResetCode( @NonNull FirebaseAuth instance, @NonNull String code); }
@Test public void testSignInWithCustomToken() { mockSuccessfulAuthResult(); when(mockFirebaseAuth.signInWithCustomToken("custom_token")).thenReturn(mockAuthResultTask); TestObserver<FirebaseUser> obs = TestObserver.create(); RxFirebaseAuth.signInWithCustomToken(mockFirebaseAuth, "custom_token").subscribe(obs); callOnComplete(mockAuthResultTask); obs.dispose(); callOnComplete(mockAuthResultTask); obs.assertNoErrors(); obs.assertComplete(); obs.assertValueCount(1); } @Test public void testSignInWithCustomToken_NotSuccessful() { mockNotSuccessfulAuthResult(new IllegalStateException()); when(mockFirebaseAuth.signInWithCustomToken("custom_token")).thenReturn(mockAuthResultTask); TestObserver<FirebaseUser> obs = TestObserver.create(); RxFirebaseAuth.signInWithCustomToken(mockFirebaseAuth, "custom_token").subscribe(obs); callOnComplete(mockAuthResultTask); obs.dispose(); callOnComplete(mockAuthResultTask); obs.assertError(IllegalStateException.class); obs.assertNoValues(); }
RxFirebaseAuth { @CheckResult @NonNull public static Single<FirebaseUser> signInWithEmailAndPassword( @NonNull FirebaseAuth instance, @NonNull String email, @NonNull String password) { return Single.create(new SignInWithEmailAndPasswordOnSubscribe(instance, email, password)); } private RxFirebaseAuth(); @CheckResult @NonNull static Observable<FirebaseAuth> authStateChanges( @NonNull FirebaseAuth instance); @CheckResult @NonNull static Single<FirebaseUser> createUserWithEmailAndPassword( @NonNull FirebaseAuth instance, @NonNull String email, @NonNull String password); @CheckResult @NonNull static Maybe<List<String>> fetchProvidersForEmail( @NonNull FirebaseAuth instance, @NonNull String email); @CheckResult @NonNull static Maybe<FirebaseUser> getCurrentUser( @NonNull final FirebaseAuth instance); @CheckResult @NonNull static Completable sendPasswordResetEmail( @NonNull FirebaseAuth instance, @NonNull String email); @CheckResult @NonNull static Single<FirebaseUser> signInAnonymously( @NonNull FirebaseAuth instance); @CheckResult @NonNull static Single<FirebaseUser> signInWithCredential( @NonNull FirebaseAuth instance, @NonNull AuthCredential credential); @CheckResult @NonNull static Single<FirebaseUser> signInWithCustomToken( @NonNull FirebaseAuth instance, @NonNull String token); @CheckResult @NonNull static Single<FirebaseUser> signInWithEmailAndPassword( @NonNull FirebaseAuth instance, @NonNull String email, @NonNull String password); @CheckResult @NonNull static Completable signOut(@NonNull FirebaseAuth instance); @CheckResult @NonNull static Completable applyActionCode(@NonNull FirebaseAuth instance, @NonNull String code); @CheckResult @NonNull static Single<ActionCodeResult> checkActionCode( @NonNull FirebaseAuth instance, @NonNull String code); @CheckResult @NonNull static Completable confirmPasswordReset( @NonNull FirebaseAuth instance, @NonNull String code, @NonNull String newPassword); @CheckResult @NonNull static Single<String> verifyPasswordResetCode( @NonNull FirebaseAuth instance, @NonNull String code); }
@Test public void testSignInWithEmailAndPassword() { mockSuccessfulAuthResult(); when(mockFirebaseAuth.signInWithEmailAndPassword("email", "password")).thenReturn( mockAuthResultTask); TestObserver<FirebaseUser> obs = TestObserver.create(); RxFirebaseAuth.signInWithEmailAndPassword(mockFirebaseAuth, "email", "password").subscribe(obs); callOnComplete(mockAuthResultTask); obs.dispose(); callOnComplete(mockAuthResultTask); obs.assertNoErrors(); obs.assertComplete(); obs.assertValueCount(1); } @Test public void testSignInWithEmailAndPassword_NotSuccessful() { mockNotSuccessfulAuthResult(new IllegalStateException()); when(mockFirebaseAuth.signInWithEmailAndPassword("email", "password")).thenReturn( mockAuthResultTask); TestObserver<FirebaseUser> obs = TestObserver.create(); RxFirebaseAuth.signInWithEmailAndPassword(mockFirebaseAuth, "email", "password").subscribe(obs); callOnComplete(mockAuthResultTask); obs.dispose(); callOnComplete(mockAuthResultTask); obs.assertError(IllegalStateException.class); obs.assertNoValues(); }
RxFirebaseAuth { @CheckResult @NonNull public static Completable signOut(@NonNull FirebaseAuth instance) { return Completable.create(new SignOutOnSubscribe(instance)); } private RxFirebaseAuth(); @CheckResult @NonNull static Observable<FirebaseAuth> authStateChanges( @NonNull FirebaseAuth instance); @CheckResult @NonNull static Single<FirebaseUser> createUserWithEmailAndPassword( @NonNull FirebaseAuth instance, @NonNull String email, @NonNull String password); @CheckResult @NonNull static Maybe<List<String>> fetchProvidersForEmail( @NonNull FirebaseAuth instance, @NonNull String email); @CheckResult @NonNull static Maybe<FirebaseUser> getCurrentUser( @NonNull final FirebaseAuth instance); @CheckResult @NonNull static Completable sendPasswordResetEmail( @NonNull FirebaseAuth instance, @NonNull String email); @CheckResult @NonNull static Single<FirebaseUser> signInAnonymously( @NonNull FirebaseAuth instance); @CheckResult @NonNull static Single<FirebaseUser> signInWithCredential( @NonNull FirebaseAuth instance, @NonNull AuthCredential credential); @CheckResult @NonNull static Single<FirebaseUser> signInWithCustomToken( @NonNull FirebaseAuth instance, @NonNull String token); @CheckResult @NonNull static Single<FirebaseUser> signInWithEmailAndPassword( @NonNull FirebaseAuth instance, @NonNull String email, @NonNull String password); @CheckResult @NonNull static Completable signOut(@NonNull FirebaseAuth instance); @CheckResult @NonNull static Completable applyActionCode(@NonNull FirebaseAuth instance, @NonNull String code); @CheckResult @NonNull static Single<ActionCodeResult> checkActionCode( @NonNull FirebaseAuth instance, @NonNull String code); @CheckResult @NonNull static Completable confirmPasswordReset( @NonNull FirebaseAuth instance, @NonNull String code, @NonNull String newPassword); @CheckResult @NonNull static Single<String> verifyPasswordResetCode( @NonNull FirebaseAuth instance, @NonNull String code); }
@Test public void testSignOut() { TestObserver obs = TestObserver.create(); RxFirebaseAuth.signOut(mockFirebaseAuth).subscribe(obs); verify(mockFirebaseAuth).signOut(); obs.dispose(); obs.assertNoErrors(); obs.assertComplete(); }
RxFirebaseAuth { @CheckResult @NonNull public static Completable applyActionCode(@NonNull FirebaseAuth instance, @NonNull String code) { return Completable.create(new ApplyActionCodeOnSubscribe(instance, code)); } private RxFirebaseAuth(); @CheckResult @NonNull static Observable<FirebaseAuth> authStateChanges( @NonNull FirebaseAuth instance); @CheckResult @NonNull static Single<FirebaseUser> createUserWithEmailAndPassword( @NonNull FirebaseAuth instance, @NonNull String email, @NonNull String password); @CheckResult @NonNull static Maybe<List<String>> fetchProvidersForEmail( @NonNull FirebaseAuth instance, @NonNull String email); @CheckResult @NonNull static Maybe<FirebaseUser> getCurrentUser( @NonNull final FirebaseAuth instance); @CheckResult @NonNull static Completable sendPasswordResetEmail( @NonNull FirebaseAuth instance, @NonNull String email); @CheckResult @NonNull static Single<FirebaseUser> signInAnonymously( @NonNull FirebaseAuth instance); @CheckResult @NonNull static Single<FirebaseUser> signInWithCredential( @NonNull FirebaseAuth instance, @NonNull AuthCredential credential); @CheckResult @NonNull static Single<FirebaseUser> signInWithCustomToken( @NonNull FirebaseAuth instance, @NonNull String token); @CheckResult @NonNull static Single<FirebaseUser> signInWithEmailAndPassword( @NonNull FirebaseAuth instance, @NonNull String email, @NonNull String password); @CheckResult @NonNull static Completable signOut(@NonNull FirebaseAuth instance); @CheckResult @NonNull static Completable applyActionCode(@NonNull FirebaseAuth instance, @NonNull String code); @CheckResult @NonNull static Single<ActionCodeResult> checkActionCode( @NonNull FirebaseAuth instance, @NonNull String code); @CheckResult @NonNull static Completable confirmPasswordReset( @NonNull FirebaseAuth instance, @NonNull String code, @NonNull String newPassword); @CheckResult @NonNull static Single<String> verifyPasswordResetCode( @NonNull FirebaseAuth instance, @NonNull String code); }
@Test public void testApplyActionCode() { TestObserver obs = TestObserver.create(); mockSuccessfulResultForTask(mockVoidTask); when(mockFirebaseAuth.applyActionCode("code")).thenReturn(mockVoidTask); RxFirebaseAuth.applyActionCode(mockFirebaseAuth, "code").subscribe(obs); verify(mockFirebaseAuth).applyActionCode("code"); callOnComplete(mockVoidTask); obs.dispose(); obs.assertNoErrors(); obs.assertComplete(); } @Test public void testApplyActionCode_NotSuccessful() { TestObserver obs = TestObserver.create(); mockNotSuccessfulResultForTask(mockVoidTask, new IllegalStateException()); when(mockFirebaseAuth.applyActionCode("code")).thenReturn(mockVoidTask); RxFirebaseAuth.applyActionCode(mockFirebaseAuth, "code").subscribe(obs); verify(mockFirebaseAuth).applyActionCode("code"); callOnComplete(mockVoidTask); obs.dispose(); callOnComplete(mockVoidTask); obs.assertError(IllegalStateException.class); obs.assertNoValues(); }
RxFirebaseAuth { @CheckResult @NonNull public static Single<FirebaseUser> createUserWithEmailAndPassword( @NonNull FirebaseAuth instance, @NonNull String email, @NonNull String password) { return Single.create(new CreateUserWithEmailAndPasswordOnSubscribe(instance, email, password)); } private RxFirebaseAuth(); @CheckResult @NonNull static Observable<FirebaseAuth> authStateChanges( @NonNull FirebaseAuth instance); @CheckResult @NonNull static Single<FirebaseUser> createUserWithEmailAndPassword( @NonNull FirebaseAuth instance, @NonNull String email, @NonNull String password); @CheckResult @NonNull static Maybe<List<String>> fetchProvidersForEmail( @NonNull FirebaseAuth instance, @NonNull String email); @CheckResult @NonNull static Maybe<FirebaseUser> getCurrentUser( @NonNull final FirebaseAuth instance); @CheckResult @NonNull static Completable sendPasswordResetEmail( @NonNull FirebaseAuth instance, @NonNull String email); @CheckResult @NonNull static Single<FirebaseUser> signInAnonymously( @NonNull FirebaseAuth instance); @CheckResult @NonNull static Single<FirebaseUser> signInWithCredential( @NonNull FirebaseAuth instance, @NonNull AuthCredential credential); @CheckResult @NonNull static Single<FirebaseUser> signInWithCustomToken( @NonNull FirebaseAuth instance, @NonNull String token); @CheckResult @NonNull static Single<FirebaseUser> signInWithEmailAndPassword( @NonNull FirebaseAuth instance, @NonNull String email, @NonNull String password); @CheckResult @NonNull static Completable signOut(@NonNull FirebaseAuth instance); @CheckResult @NonNull static Completable applyActionCode(@NonNull FirebaseAuth instance, @NonNull String code); @CheckResult @NonNull static Single<ActionCodeResult> checkActionCode( @NonNull FirebaseAuth instance, @NonNull String code); @CheckResult @NonNull static Completable confirmPasswordReset( @NonNull FirebaseAuth instance, @NonNull String code, @NonNull String newPassword); @CheckResult @NonNull static Single<String> verifyPasswordResetCode( @NonNull FirebaseAuth instance, @NonNull String code); }
@Test public void testCreateUserWithEmailAndPassword() { when(mockFirebaseUser.getEmail()).thenReturn("[email protected]"); mockSuccessfulAuthResult(); when(mockFirebaseAuth.createUserWithEmailAndPassword("[email protected]", "password")).thenReturn( mockAuthResultTask); TestObserver<FirebaseUser> obs = TestObserver.create(); RxFirebaseAuth.createUserWithEmailAndPassword(mockFirebaseAuth, "[email protected]", "password") .subscribe(obs); callOnComplete(mockAuthResultTask); obs.dispose(); callOnComplete(mockAuthResultTask); obs.assertNoErrors(); obs.assertComplete(); obs.assertValue(new Predicate<FirebaseUser>() { @Override public boolean test(FirebaseUser firebaseUser) throws Exception { return "[email protected]".equals(firebaseUser.getEmail()); } }); } @Test public void testCreateUserWithEmailAndPassword_NotSuccessful() { when(mockFirebaseUser.getEmail()).thenReturn("[email protected]"); mockNotSuccessfulAuthResult(new IllegalStateException()); when(mockFirebaseAuth.createUserWithEmailAndPassword("[email protected]", "password")).thenReturn( mockAuthResultTask); TestObserver<FirebaseUser> obs = TestObserver.create(); RxFirebaseAuth.createUserWithEmailAndPassword(mockFirebaseAuth, "[email protected]", "password") .subscribe(obs); callOnComplete(mockAuthResultTask); obs.dispose(); callOnComplete(mockAuthResultTask); obs.assertError(IllegalStateException.class); obs.assertNoValues(); }
RxFirebaseAuth { @CheckResult @NonNull public static Single<ActionCodeResult> checkActionCode( @NonNull FirebaseAuth instance, @NonNull String code) { return Single.create(new CheckActionCodeOnSubscribe(instance, code)); } private RxFirebaseAuth(); @CheckResult @NonNull static Observable<FirebaseAuth> authStateChanges( @NonNull FirebaseAuth instance); @CheckResult @NonNull static Single<FirebaseUser> createUserWithEmailAndPassword( @NonNull FirebaseAuth instance, @NonNull String email, @NonNull String password); @CheckResult @NonNull static Maybe<List<String>> fetchProvidersForEmail( @NonNull FirebaseAuth instance, @NonNull String email); @CheckResult @NonNull static Maybe<FirebaseUser> getCurrentUser( @NonNull final FirebaseAuth instance); @CheckResult @NonNull static Completable sendPasswordResetEmail( @NonNull FirebaseAuth instance, @NonNull String email); @CheckResult @NonNull static Single<FirebaseUser> signInAnonymously( @NonNull FirebaseAuth instance); @CheckResult @NonNull static Single<FirebaseUser> signInWithCredential( @NonNull FirebaseAuth instance, @NonNull AuthCredential credential); @CheckResult @NonNull static Single<FirebaseUser> signInWithCustomToken( @NonNull FirebaseAuth instance, @NonNull String token); @CheckResult @NonNull static Single<FirebaseUser> signInWithEmailAndPassword( @NonNull FirebaseAuth instance, @NonNull String email, @NonNull String password); @CheckResult @NonNull static Completable signOut(@NonNull FirebaseAuth instance); @CheckResult @NonNull static Completable applyActionCode(@NonNull FirebaseAuth instance, @NonNull String code); @CheckResult @NonNull static Single<ActionCodeResult> checkActionCode( @NonNull FirebaseAuth instance, @NonNull String code); @CheckResult @NonNull static Completable confirmPasswordReset( @NonNull FirebaseAuth instance, @NonNull String code, @NonNull String newPassword); @CheckResult @NonNull static Single<String> verifyPasswordResetCode( @NonNull FirebaseAuth instance, @NonNull String code); }
@Test public void testCheckActionCode() { when(mockActionCodeResult.getOperation()).thenReturn(ActionCodeResult.VERIFY_EMAIL); when(mockActionCodeResult.getData(ActionCodeResult.EMAIL)).thenReturn("[email protected]"); mockSuccessfulResultForTask(mockActionCodeResultTask, mockActionCodeResult); when(mockFirebaseAuth.checkActionCode("code")).thenReturn(mockActionCodeResultTask); TestObserver<ActionCodeResult> obs = TestObserver.create(); RxFirebaseAuth.checkActionCode(mockFirebaseAuth, "code").subscribe(obs); callOnComplete(mockActionCodeResultTask); obs.dispose(); callOnComplete(mockActionCodeResultTask); obs.assertNoErrors(); obs.assertComplete(); obs.assertValueCount(1); obs.assertValue(new Predicate<ActionCodeResult>() { @Override public boolean test(ActionCodeResult result) throws Exception { return result.getOperation() == ActionCodeResult.VERIFY_EMAIL && "[email protected]".equals( result.getData(ActionCodeResult.EMAIL)); } }); } @Test public void testCheckActionCode_NotSuccessful() { mockNotSuccessfulResultForTask(mockActionCodeResultTask, new IllegalStateException()); when(mockFirebaseAuth.checkActionCode("code")).thenReturn(mockActionCodeResultTask); TestObserver<ActionCodeResult> obs = TestObserver.create(); RxFirebaseAuth.checkActionCode(mockFirebaseAuth, "code").subscribe(obs); callOnComplete(mockActionCodeResultTask); obs.dispose(); callOnComplete(mockActionCodeResultTask); obs.assertError(IllegalStateException.class); obs.assertNoValues(); }
RxFirebaseAuth { @CheckResult @NonNull public static Completable confirmPasswordReset( @NonNull FirebaseAuth instance, @NonNull String code, @NonNull String newPassword) { return Completable.create(new ConfirmPasswordResetOnSubscribe(instance, code, newPassword)); } private RxFirebaseAuth(); @CheckResult @NonNull static Observable<FirebaseAuth> authStateChanges( @NonNull FirebaseAuth instance); @CheckResult @NonNull static Single<FirebaseUser> createUserWithEmailAndPassword( @NonNull FirebaseAuth instance, @NonNull String email, @NonNull String password); @CheckResult @NonNull static Maybe<List<String>> fetchProvidersForEmail( @NonNull FirebaseAuth instance, @NonNull String email); @CheckResult @NonNull static Maybe<FirebaseUser> getCurrentUser( @NonNull final FirebaseAuth instance); @CheckResult @NonNull static Completable sendPasswordResetEmail( @NonNull FirebaseAuth instance, @NonNull String email); @CheckResult @NonNull static Single<FirebaseUser> signInAnonymously( @NonNull FirebaseAuth instance); @CheckResult @NonNull static Single<FirebaseUser> signInWithCredential( @NonNull FirebaseAuth instance, @NonNull AuthCredential credential); @CheckResult @NonNull static Single<FirebaseUser> signInWithCustomToken( @NonNull FirebaseAuth instance, @NonNull String token); @CheckResult @NonNull static Single<FirebaseUser> signInWithEmailAndPassword( @NonNull FirebaseAuth instance, @NonNull String email, @NonNull String password); @CheckResult @NonNull static Completable signOut(@NonNull FirebaseAuth instance); @CheckResult @NonNull static Completable applyActionCode(@NonNull FirebaseAuth instance, @NonNull String code); @CheckResult @NonNull static Single<ActionCodeResult> checkActionCode( @NonNull FirebaseAuth instance, @NonNull String code); @CheckResult @NonNull static Completable confirmPasswordReset( @NonNull FirebaseAuth instance, @NonNull String code, @NonNull String newPassword); @CheckResult @NonNull static Single<String> verifyPasswordResetCode( @NonNull FirebaseAuth instance, @NonNull String code); }
@Test public void testConfirmPasswordReset() { TestObserver obs = TestObserver.create(); mockSuccessfulResultForTask(mockVoidTask); when(mockFirebaseAuth.confirmPasswordReset("code", "password")).thenReturn(mockVoidTask); RxFirebaseAuth.confirmPasswordReset(mockFirebaseAuth, "code", "password").subscribe(obs); verify(mockFirebaseAuth).confirmPasswordReset("code", "password"); callOnComplete(mockVoidTask); obs.dispose(); obs.assertNoErrors(); obs.assertComplete(); } @Test public void testConfirmPasswordReset_NotSuccessful() { TestObserver obs = TestObserver.create(); mockNotSuccessfulResultForTask(mockVoidTask, new IllegalStateException()); when(mockFirebaseAuth.confirmPasswordReset("code", "password")).thenReturn(mockVoidTask); RxFirebaseAuth.confirmPasswordReset(mockFirebaseAuth, "code", "password").subscribe(obs); verify(mockFirebaseAuth).confirmPasswordReset("code", "password"); callOnComplete(mockVoidTask); obs.dispose(); callOnComplete(mockVoidTask); obs.assertError(IllegalStateException.class); obs.assertNoValues(); }
RxFirebaseAuth { @CheckResult @NonNull public static Single<String> verifyPasswordResetCode( @NonNull FirebaseAuth instance, @NonNull String code) { return Single.create(new VerifyPasswordResetCodeOnSubscribe(instance, code)); } private RxFirebaseAuth(); @CheckResult @NonNull static Observable<FirebaseAuth> authStateChanges( @NonNull FirebaseAuth instance); @CheckResult @NonNull static Single<FirebaseUser> createUserWithEmailAndPassword( @NonNull FirebaseAuth instance, @NonNull String email, @NonNull String password); @CheckResult @NonNull static Maybe<List<String>> fetchProvidersForEmail( @NonNull FirebaseAuth instance, @NonNull String email); @CheckResult @NonNull static Maybe<FirebaseUser> getCurrentUser( @NonNull final FirebaseAuth instance); @CheckResult @NonNull static Completable sendPasswordResetEmail( @NonNull FirebaseAuth instance, @NonNull String email); @CheckResult @NonNull static Single<FirebaseUser> signInAnonymously( @NonNull FirebaseAuth instance); @CheckResult @NonNull static Single<FirebaseUser> signInWithCredential( @NonNull FirebaseAuth instance, @NonNull AuthCredential credential); @CheckResult @NonNull static Single<FirebaseUser> signInWithCustomToken( @NonNull FirebaseAuth instance, @NonNull String token); @CheckResult @NonNull static Single<FirebaseUser> signInWithEmailAndPassword( @NonNull FirebaseAuth instance, @NonNull String email, @NonNull String password); @CheckResult @NonNull static Completable signOut(@NonNull FirebaseAuth instance); @CheckResult @NonNull static Completable applyActionCode(@NonNull FirebaseAuth instance, @NonNull String code); @CheckResult @NonNull static Single<ActionCodeResult> checkActionCode( @NonNull FirebaseAuth instance, @NonNull String code); @CheckResult @NonNull static Completable confirmPasswordReset( @NonNull FirebaseAuth instance, @NonNull String code, @NonNull String newPassword); @CheckResult @NonNull static Single<String> verifyPasswordResetCode( @NonNull FirebaseAuth instance, @NonNull String code); }
@Test public void testVerifyPasswordResetCode() { mockSuccessfulResultForTask(mockStringTask, "[email protected]"); when(mockFirebaseAuth.verifyPasswordResetCode("code")).thenReturn(mockStringTask); TestObserver<String> obs = TestObserver.create(); RxFirebaseAuth.verifyPasswordResetCode(mockFirebaseAuth, "code").subscribe(obs); callOnComplete(mockStringTask); obs.dispose(); callOnComplete(mockStringTask); obs.assertNoErrors(); obs.assertComplete(); obs.assertValueCount(1); obs.assertValue(new Predicate<String>() { @Override public boolean test(String result) throws Exception { return "[email protected]".equals(result); } }); } @Test public void testVerifyPasswordResetCode_NotSuccessful() { mockNotSuccessfulResultForTask(mockStringTask, new IllegalStateException()); when(mockFirebaseAuth.verifyPasswordResetCode("code")).thenReturn(mockStringTask); TestObserver<String> obs = TestObserver.create(); RxFirebaseAuth.verifyPasswordResetCode(mockFirebaseAuth, "code").subscribe(obs); callOnComplete(mockStringTask); obs.dispose(); callOnComplete(mockStringTask); obs.assertError(IllegalStateException.class); obs.assertNoValues(); }
RxFirebaseUser { @CheckResult @NonNull public static Completable delete(@NonNull FirebaseUser user) { return Completable.create(new UserDeleteOnSubscribe(user)); } private RxFirebaseUser(); @CheckResult @NonNull static Completable delete(@NonNull FirebaseUser user); @CheckResult @NonNull static Single<String> getToken(@NonNull FirebaseUser user, boolean forceRefresh); @CheckResult @NonNull static Single<AuthResult> linkWithCredential( @NonNull FirebaseUser user, @NonNull AuthCredential credential); @CheckResult @NonNull static Completable reauthenticate(@NonNull FirebaseUser user, @NonNull AuthCredential credential); @CheckResult @NonNull static Completable reload(@NonNull FirebaseUser user); @CheckResult @NonNull static Completable sendEmailVerification( @NonNull FirebaseUser user); @CheckResult @NonNull static Single<AuthResult> unlink(@NonNull FirebaseUser user, @NonNull String provider); @CheckResult @NonNull static Completable updateEmail(@NonNull FirebaseUser user, @NonNull String email); @CheckResult @NonNull static Completable updatePassword(@NonNull FirebaseUser user, @NonNull String password); @CheckResult @NonNull static Completable updateProfile(@NonNull FirebaseUser user, @NonNull UserProfileChangeRequest request); }
@Test public void testDelete() { mockVoidResult(true); when(mockFirebaseUser.delete()).thenReturn(mockVoidTaskResult); TestObserver obs = TestObserver.create(); RxFirebaseUser.delete(mockFirebaseUser).subscribe(obs); callOnComplete(mockVoidTaskResult); obs.dispose(); callOnComplete(mockVoidTaskResult); obs.assertNoErrors(); obs.assertComplete(); } @Test public void testDelete_notSuccessful() { mockNotSuccessfulVoidResult(new IllegalStateException()); when(mockFirebaseUser.delete()).thenReturn(mockVoidTaskResult); TestObserver obs = TestObserver.create(); RxFirebaseUser.delete(mockFirebaseUser).subscribe(obs); callOnComplete(mockVoidTaskResult); obs.dispose(); callOnComplete(mockVoidTaskResult); obs.assertError(IllegalStateException.class); obs.assertNotComplete(); }
RxFirebaseUser { @CheckResult @NonNull public static Single<String> getToken(@NonNull FirebaseUser user, boolean forceRefresh) { return Single.create(new UserGetTokenOnSubscribe(user, forceRefresh)); } private RxFirebaseUser(); @CheckResult @NonNull static Completable delete(@NonNull FirebaseUser user); @CheckResult @NonNull static Single<String> getToken(@NonNull FirebaseUser user, boolean forceRefresh); @CheckResult @NonNull static Single<AuthResult> linkWithCredential( @NonNull FirebaseUser user, @NonNull AuthCredential credential); @CheckResult @NonNull static Completable reauthenticate(@NonNull FirebaseUser user, @NonNull AuthCredential credential); @CheckResult @NonNull static Completable reload(@NonNull FirebaseUser user); @CheckResult @NonNull static Completable sendEmailVerification( @NonNull FirebaseUser user); @CheckResult @NonNull static Single<AuthResult> unlink(@NonNull FirebaseUser user, @NonNull String provider); @CheckResult @NonNull static Completable updateEmail(@NonNull FirebaseUser user, @NonNull String email); @CheckResult @NonNull static Completable updatePassword(@NonNull FirebaseUser user, @NonNull String password); @CheckResult @NonNull static Completable updateProfile(@NonNull FirebaseUser user, @NonNull UserProfileChangeRequest request); }
@Test public void testGetToken() { mockSuccessfulTokenResult("token"); when(mockFirebaseUser.getToken(true)).thenReturn(mockGetTokenTaskResult); TestObserver<String> obs = TestObserver.create(); RxFirebaseUser.getToken(mockFirebaseUser, true).subscribe(obs); callOnComplete(mockGetTokenTaskResult); obs.dispose(); callOnComplete(mockGetTokenTaskResult); obs.assertNoErrors(); obs.assertComplete(); obs.assertValue("token"); } @Test public void testGetToken_notSuccessful() { mockNotSuccessfulTokenResult(new IllegalStateException()); when(mockFirebaseUser.getToken(true)).thenReturn(mockGetTokenTaskResult); TestObserver<String> obs = TestObserver.create(); RxFirebaseUser.getToken(mockFirebaseUser, true).subscribe(obs); callOnComplete(mockGetTokenTaskResult); obs.dispose(); callOnComplete(mockGetTokenTaskResult); obs.assertError(IllegalStateException.class); obs.assertNoValues(); }
RxFirebaseUser { @CheckResult @NonNull public static Single<AuthResult> linkWithCredential( @NonNull FirebaseUser user, @NonNull AuthCredential credential) { return Single.create(new UserLinkWithCredentialOnSubscribe(user, credential)); } private RxFirebaseUser(); @CheckResult @NonNull static Completable delete(@NonNull FirebaseUser user); @CheckResult @NonNull static Single<String> getToken(@NonNull FirebaseUser user, boolean forceRefresh); @CheckResult @NonNull static Single<AuthResult> linkWithCredential( @NonNull FirebaseUser user, @NonNull AuthCredential credential); @CheckResult @NonNull static Completable reauthenticate(@NonNull FirebaseUser user, @NonNull AuthCredential credential); @CheckResult @NonNull static Completable reload(@NonNull FirebaseUser user); @CheckResult @NonNull static Completable sendEmailVerification( @NonNull FirebaseUser user); @CheckResult @NonNull static Single<AuthResult> unlink(@NonNull FirebaseUser user, @NonNull String provider); @CheckResult @NonNull static Completable updateEmail(@NonNull FirebaseUser user, @NonNull String email); @CheckResult @NonNull static Completable updatePassword(@NonNull FirebaseUser user, @NonNull String password); @CheckResult @NonNull static Completable updateProfile(@NonNull FirebaseUser user, @NonNull UserProfileChangeRequest request); }
@Test public void testLinkWithCredential() { mockSuccessfulAuthResult(); when(mockFirebaseUser.linkWithCredential(mockAuthCredential)).thenReturn(mockAuthTaskResult); TestObserver<AuthResult> obs = TestObserver.create(); RxFirebaseUser.linkWithCredential(mockFirebaseUser, mockAuthCredential).subscribe(obs); callOnComplete(mockAuthTaskResult); obs.dispose(); callOnComplete(mockAuthTaskResult); obs.assertNoErrors(); obs.assertComplete(); obs.assertValueCount(1); } @Test public void testLinkWithCredential_notSuccessful() { mockNotSuccessfulAuthResult(new IllegalStateException()); when(mockFirebaseUser.linkWithCredential(mockAuthCredential)).thenReturn(mockAuthTaskResult); TestObserver<AuthResult> obs = TestObserver.create(); RxFirebaseUser.linkWithCredential(mockFirebaseUser, mockAuthCredential).subscribe(obs); callOnComplete(mockAuthTaskResult); obs.dispose(); callOnComplete(mockAuthTaskResult); obs.assertError(IllegalStateException.class); obs.assertNoValues(); }
RxFirebaseUser { @CheckResult @NonNull public static Completable reauthenticate(@NonNull FirebaseUser user, @NonNull AuthCredential credential) { return Completable.create(new UserReauthenticateOnSubscribe(user, credential)); } private RxFirebaseUser(); @CheckResult @NonNull static Completable delete(@NonNull FirebaseUser user); @CheckResult @NonNull static Single<String> getToken(@NonNull FirebaseUser user, boolean forceRefresh); @CheckResult @NonNull static Single<AuthResult> linkWithCredential( @NonNull FirebaseUser user, @NonNull AuthCredential credential); @CheckResult @NonNull static Completable reauthenticate(@NonNull FirebaseUser user, @NonNull AuthCredential credential); @CheckResult @NonNull static Completable reload(@NonNull FirebaseUser user); @CheckResult @NonNull static Completable sendEmailVerification( @NonNull FirebaseUser user); @CheckResult @NonNull static Single<AuthResult> unlink(@NonNull FirebaseUser user, @NonNull String provider); @CheckResult @NonNull static Completable updateEmail(@NonNull FirebaseUser user, @NonNull String email); @CheckResult @NonNull static Completable updatePassword(@NonNull FirebaseUser user, @NonNull String password); @CheckResult @NonNull static Completable updateProfile(@NonNull FirebaseUser user, @NonNull UserProfileChangeRequest request); }
@Test public void testReauthenticate() { mockVoidResult(true); when(mockFirebaseUser.reauthenticate(mockAuthCredential)).thenReturn(mockVoidTaskResult); TestObserver obs = TestObserver.create(); RxFirebaseUser.reauthenticate(mockFirebaseUser, mockAuthCredential).subscribe(obs); callOnComplete(mockVoidTaskResult); obs.dispose(); callOnComplete(mockVoidTaskResult); obs.assertNoErrors(); obs.assertComplete(); } @Test public void testReauthenticate_notSuccessful() { mockNotSuccessfulVoidResult(new IllegalStateException()); when(mockFirebaseUser.reauthenticate(mockAuthCredential)).thenReturn(mockVoidTaskResult); TestObserver obs = TestObserver.create(); RxFirebaseUser.reauthenticate(mockFirebaseUser, mockAuthCredential).subscribe(obs); callOnComplete(mockVoidTaskResult); obs.dispose(); callOnComplete(mockVoidTaskResult); obs.assertError(IllegalStateException.class); obs.assertNotComplete(); }
RxFirebaseUser { @CheckResult @NonNull public static Completable reload(@NonNull FirebaseUser user) { return Completable.create(new UserReloadOnSubscribe(user)); } private RxFirebaseUser(); @CheckResult @NonNull static Completable delete(@NonNull FirebaseUser user); @CheckResult @NonNull static Single<String> getToken(@NonNull FirebaseUser user, boolean forceRefresh); @CheckResult @NonNull static Single<AuthResult> linkWithCredential( @NonNull FirebaseUser user, @NonNull AuthCredential credential); @CheckResult @NonNull static Completable reauthenticate(@NonNull FirebaseUser user, @NonNull AuthCredential credential); @CheckResult @NonNull static Completable reload(@NonNull FirebaseUser user); @CheckResult @NonNull static Completable sendEmailVerification( @NonNull FirebaseUser user); @CheckResult @NonNull static Single<AuthResult> unlink(@NonNull FirebaseUser user, @NonNull String provider); @CheckResult @NonNull static Completable updateEmail(@NonNull FirebaseUser user, @NonNull String email); @CheckResult @NonNull static Completable updatePassword(@NonNull FirebaseUser user, @NonNull String password); @CheckResult @NonNull static Completable updateProfile(@NonNull FirebaseUser user, @NonNull UserProfileChangeRequest request); }
@Test public void testReload() { mockVoidResult(true); when(mockFirebaseUser.reload()).thenReturn(mockVoidTaskResult); TestObserver obs = TestObserver.create(); RxFirebaseUser.reload(mockFirebaseUser).subscribe(obs); callOnComplete(mockVoidTaskResult); obs.dispose(); callOnComplete(mockVoidTaskResult); obs.assertNoErrors(); obs.assertComplete(); } @Test public void testReload_notSuccessful() { mockNotSuccessfulVoidResult(new IllegalStateException()); when(mockFirebaseUser.reload()).thenReturn(mockVoidTaskResult); TestObserver obs = TestObserver.create(); RxFirebaseUser.reload(mockFirebaseUser).subscribe(obs); callOnComplete(mockVoidTaskResult); obs.dispose(); callOnComplete(mockVoidTaskResult); obs.assertError(IllegalStateException.class); obs.assertNotComplete(); }
RxFirebaseUser { @CheckResult @NonNull public static Completable sendEmailVerification( @NonNull FirebaseUser user) { return Completable.create(new UserSendEmailVerificationOnSubscribe(user)); } private RxFirebaseUser(); @CheckResult @NonNull static Completable delete(@NonNull FirebaseUser user); @CheckResult @NonNull static Single<String> getToken(@NonNull FirebaseUser user, boolean forceRefresh); @CheckResult @NonNull static Single<AuthResult> linkWithCredential( @NonNull FirebaseUser user, @NonNull AuthCredential credential); @CheckResult @NonNull static Completable reauthenticate(@NonNull FirebaseUser user, @NonNull AuthCredential credential); @CheckResult @NonNull static Completable reload(@NonNull FirebaseUser user); @CheckResult @NonNull static Completable sendEmailVerification( @NonNull FirebaseUser user); @CheckResult @NonNull static Single<AuthResult> unlink(@NonNull FirebaseUser user, @NonNull String provider); @CheckResult @NonNull static Completable updateEmail(@NonNull FirebaseUser user, @NonNull String email); @CheckResult @NonNull static Completable updatePassword(@NonNull FirebaseUser user, @NonNull String password); @CheckResult @NonNull static Completable updateProfile(@NonNull FirebaseUser user, @NonNull UserProfileChangeRequest request); }
@Test public void testSendEmailVerification() { mockVoidResult(true); when(mockFirebaseUser.sendEmailVerification()).thenReturn(mockVoidTaskResult); TestObserver obs = TestObserver.create(); RxFirebaseUser.sendEmailVerification(mockFirebaseUser).subscribe(obs); callOnComplete(mockVoidTaskResult); obs.dispose(); callOnComplete(mockVoidTaskResult); obs.assertNoErrors(); obs.assertComplete(); } @Test public void testSendEmailVerification_notSuccessful() { mockNotSuccessfulVoidResult(new IllegalStateException()); when(mockFirebaseUser.sendEmailVerification()).thenReturn(mockVoidTaskResult); TestObserver obs = TestObserver.create(); RxFirebaseUser.sendEmailVerification(mockFirebaseUser).subscribe(obs); callOnComplete(mockVoidTaskResult); obs.dispose(); callOnComplete(mockVoidTaskResult); obs.assertError(IllegalStateException.class); obs.assertNotComplete(); }
RxFirebaseUser { @CheckResult @NonNull public static Single<AuthResult> unlink(@NonNull FirebaseUser user, @NonNull String provider) { return Single.create(new UserUnlinkOnSubscribe(user, provider)); } private RxFirebaseUser(); @CheckResult @NonNull static Completable delete(@NonNull FirebaseUser user); @CheckResult @NonNull static Single<String> getToken(@NonNull FirebaseUser user, boolean forceRefresh); @CheckResult @NonNull static Single<AuthResult> linkWithCredential( @NonNull FirebaseUser user, @NonNull AuthCredential credential); @CheckResult @NonNull static Completable reauthenticate(@NonNull FirebaseUser user, @NonNull AuthCredential credential); @CheckResult @NonNull static Completable reload(@NonNull FirebaseUser user); @CheckResult @NonNull static Completable sendEmailVerification( @NonNull FirebaseUser user); @CheckResult @NonNull static Single<AuthResult> unlink(@NonNull FirebaseUser user, @NonNull String provider); @CheckResult @NonNull static Completable updateEmail(@NonNull FirebaseUser user, @NonNull String email); @CheckResult @NonNull static Completable updatePassword(@NonNull FirebaseUser user, @NonNull String password); @CheckResult @NonNull static Completable updateProfile(@NonNull FirebaseUser user, @NonNull UserProfileChangeRequest request); }
@Test public void testUnlink() { mockSuccessfulAuthResult(); when(mockFirebaseUser.unlink("provider")).thenReturn(mockAuthTaskResult); TestObserver<AuthResult> obs = TestObserver.create(); RxFirebaseUser.unlink(mockFirebaseUser, "provider").subscribe(obs); callOnComplete(mockAuthTaskResult); obs.dispose(); callOnComplete(mockAuthTaskResult); obs.assertNoErrors(); obs.assertComplete(); obs.assertValueCount(1); } @Test public void testUnlink_notSuccessful() { mockNotSuccessfulAuthResult(new IllegalStateException()); when(mockFirebaseUser.unlink("provider")).thenReturn(mockAuthTaskResult); TestObserver<AuthResult> obs = TestObserver.create(); RxFirebaseUser.unlink(mockFirebaseUser, "provider").subscribe(obs); callOnComplete(mockAuthTaskResult); obs.dispose(); callOnComplete(mockAuthTaskResult); obs.assertError(IllegalStateException.class); obs.assertNoValues(); }
RxFirebaseAuth { @CheckResult @NonNull public static Maybe<List<String>> fetchProvidersForEmail( @NonNull FirebaseAuth instance, @NonNull String email) { return Maybe.create(new FetchProvidersForEmailOnSubscribe(instance, email)); } private RxFirebaseAuth(); @CheckResult @NonNull static Observable<FirebaseAuth> authStateChanges( @NonNull FirebaseAuth instance); @CheckResult @NonNull static Single<FirebaseUser> createUserWithEmailAndPassword( @NonNull FirebaseAuth instance, @NonNull String email, @NonNull String password); @CheckResult @NonNull static Maybe<List<String>> fetchProvidersForEmail( @NonNull FirebaseAuth instance, @NonNull String email); @CheckResult @NonNull static Maybe<FirebaseUser> getCurrentUser( @NonNull final FirebaseAuth instance); @CheckResult @NonNull static Completable sendPasswordResetEmail( @NonNull FirebaseAuth instance, @NonNull String email); @CheckResult @NonNull static Single<FirebaseUser> signInAnonymously( @NonNull FirebaseAuth instance); @CheckResult @NonNull static Single<FirebaseUser> signInWithCredential( @NonNull FirebaseAuth instance, @NonNull AuthCredential credential); @CheckResult @NonNull static Single<FirebaseUser> signInWithCustomToken( @NonNull FirebaseAuth instance, @NonNull String token); @CheckResult @NonNull static Single<FirebaseUser> signInWithEmailAndPassword( @NonNull FirebaseAuth instance, @NonNull String email, @NonNull String password); @CheckResult @NonNull static Completable signOut(@NonNull FirebaseAuth instance); @CheckResult @NonNull static Completable applyActionCode(@NonNull FirebaseAuth instance, @NonNull String code); @CheckResult @NonNull static Single<ActionCodeResult> checkActionCode( @NonNull FirebaseAuth instance, @NonNull String code); @CheckResult @NonNull static Completable confirmPasswordReset( @NonNull FirebaseAuth instance, @NonNull String code, @NonNull String newPassword); @CheckResult @NonNull static Single<String> verifyPasswordResetCode( @NonNull FirebaseAuth instance, @NonNull String code); }
@Test public void testFetchProvidersForEmail() { when(mockFirebaseAuth.fetchProvidersForEmail("[email protected]")).thenReturn(mockFetchProvidersTask); when(mockProviderQueryResult.getProviders()).thenReturn(Arrays.asList("bar.com")); mockSuccessfulResultForTask(mockFetchProvidersTask, mockProviderQueryResult); when(mockFirebaseAuth.fetchProvidersForEmail("[email protected]")).thenReturn(mockFetchProvidersTask); TestObserver<List<String>> obs = TestObserver.create(); RxFirebaseAuth.fetchProvidersForEmail(mockFirebaseAuth, "[email protected]").subscribe(obs); callOnComplete(mockFetchProvidersTask); obs.dispose(); callOnComplete(mockFetchProvidersTask); obs.assertNoErrors(); obs.assertComplete(); obs.assertValue(Arrays.asList("bar.com")); } @Test public void testFetchProvidersForEmail_NotSuccessful() { when(mockFirebaseAuth.fetchProvidersForEmail("[email protected]")).thenReturn(mockFetchProvidersTask); mockNotSuccessfulFetchProvidersResult(new IllegalStateException()); when(mockFirebaseAuth.fetchProvidersForEmail("[email protected]")).thenReturn(mockFetchProvidersTask); TestObserver<List<String>> obs = TestObserver.create(); RxFirebaseAuth.fetchProvidersForEmail(mockFirebaseAuth, "[email protected]").subscribe(obs); callOnComplete(mockFetchProvidersTask); obs.dispose(); callOnComplete(mockFetchProvidersTask); obs.assertError(IllegalStateException.class); obs.assertNoValues(); }
RxFirebaseUser { @CheckResult @NonNull public static Completable updateEmail(@NonNull FirebaseUser user, @NonNull String email) { return Completable.create(new UserUpdateEmailOnSubscribe(user, email)); } private RxFirebaseUser(); @CheckResult @NonNull static Completable delete(@NonNull FirebaseUser user); @CheckResult @NonNull static Single<String> getToken(@NonNull FirebaseUser user, boolean forceRefresh); @CheckResult @NonNull static Single<AuthResult> linkWithCredential( @NonNull FirebaseUser user, @NonNull AuthCredential credential); @CheckResult @NonNull static Completable reauthenticate(@NonNull FirebaseUser user, @NonNull AuthCredential credential); @CheckResult @NonNull static Completable reload(@NonNull FirebaseUser user); @CheckResult @NonNull static Completable sendEmailVerification( @NonNull FirebaseUser user); @CheckResult @NonNull static Single<AuthResult> unlink(@NonNull FirebaseUser user, @NonNull String provider); @CheckResult @NonNull static Completable updateEmail(@NonNull FirebaseUser user, @NonNull String email); @CheckResult @NonNull static Completable updatePassword(@NonNull FirebaseUser user, @NonNull String password); @CheckResult @NonNull static Completable updateProfile(@NonNull FirebaseUser user, @NonNull UserProfileChangeRequest request); }
@Test public void testUpdateEmail() { mockVoidResult(true); when(mockFirebaseUser.updateEmail("[email protected]")).thenReturn(mockVoidTaskResult); TestObserver obs = TestObserver.create(); RxFirebaseUser.updateEmail(mockFirebaseUser, "[email protected]").subscribe(obs); callOnComplete(mockVoidTaskResult); obs.dispose(); callOnComplete(mockVoidTaskResult); obs.assertNoErrors(); obs.assertComplete(); } @Test public void testUpdateEmail_notSuccessful() { mockNotSuccessfulVoidResult(new IllegalStateException()); when(mockFirebaseUser.updateEmail("[email protected]")).thenReturn(mockVoidTaskResult); TestObserver obs = TestObserver.create(); RxFirebaseUser.updateEmail(mockFirebaseUser, "[email protected]").subscribe(obs); callOnComplete(mockVoidTaskResult); obs.dispose(); callOnComplete(mockVoidTaskResult); obs.assertError(IllegalStateException.class); obs.assertNotComplete(); }
RxFirebaseUser { @CheckResult @NonNull public static Completable updatePassword(@NonNull FirebaseUser user, @NonNull String password) { return Completable.create(new UserUpdatePasswordOnSubscribe(user, password)); } private RxFirebaseUser(); @CheckResult @NonNull static Completable delete(@NonNull FirebaseUser user); @CheckResult @NonNull static Single<String> getToken(@NonNull FirebaseUser user, boolean forceRefresh); @CheckResult @NonNull static Single<AuthResult> linkWithCredential( @NonNull FirebaseUser user, @NonNull AuthCredential credential); @CheckResult @NonNull static Completable reauthenticate(@NonNull FirebaseUser user, @NonNull AuthCredential credential); @CheckResult @NonNull static Completable reload(@NonNull FirebaseUser user); @CheckResult @NonNull static Completable sendEmailVerification( @NonNull FirebaseUser user); @CheckResult @NonNull static Single<AuthResult> unlink(@NonNull FirebaseUser user, @NonNull String provider); @CheckResult @NonNull static Completable updateEmail(@NonNull FirebaseUser user, @NonNull String email); @CheckResult @NonNull static Completable updatePassword(@NonNull FirebaseUser user, @NonNull String password); @CheckResult @NonNull static Completable updateProfile(@NonNull FirebaseUser user, @NonNull UserProfileChangeRequest request); }
@Test public void testUpdatePassword() { mockVoidResult(true); when(mockFirebaseUser.updatePassword("password")).thenReturn(mockVoidTaskResult); TestObserver obs = TestObserver.create(); RxFirebaseUser.updatePassword(mockFirebaseUser, "password").subscribe(obs); callOnComplete(mockVoidTaskResult); obs.dispose(); callOnComplete(mockVoidTaskResult); obs.assertNoErrors(); obs.assertComplete(); } @Test public void testUpdatePassword_notSuccessful() { mockNotSuccessfulVoidResult(new IllegalStateException()); when(mockFirebaseUser.updatePassword("password")).thenReturn(mockVoidTaskResult); TestObserver obs = TestObserver.create(); RxFirebaseUser.updatePassword(mockFirebaseUser, "password").subscribe(obs); callOnComplete(mockVoidTaskResult); obs.dispose(); callOnComplete(mockVoidTaskResult); obs.assertError(IllegalStateException.class); obs.assertNotComplete(); }
RxFirebaseUser { @CheckResult @NonNull public static Completable updateProfile(@NonNull FirebaseUser user, @NonNull UserProfileChangeRequest request) { return Completable.create(new UserUpdateProfileOnSubscribe(user, request)); } private RxFirebaseUser(); @CheckResult @NonNull static Completable delete(@NonNull FirebaseUser user); @CheckResult @NonNull static Single<String> getToken(@NonNull FirebaseUser user, boolean forceRefresh); @CheckResult @NonNull static Single<AuthResult> linkWithCredential( @NonNull FirebaseUser user, @NonNull AuthCredential credential); @CheckResult @NonNull static Completable reauthenticate(@NonNull FirebaseUser user, @NonNull AuthCredential credential); @CheckResult @NonNull static Completable reload(@NonNull FirebaseUser user); @CheckResult @NonNull static Completable sendEmailVerification( @NonNull FirebaseUser user); @CheckResult @NonNull static Single<AuthResult> unlink(@NonNull FirebaseUser user, @NonNull String provider); @CheckResult @NonNull static Completable updateEmail(@NonNull FirebaseUser user, @NonNull String email); @CheckResult @NonNull static Completable updatePassword(@NonNull FirebaseUser user, @NonNull String password); @CheckResult @NonNull static Completable updateProfile(@NonNull FirebaseUser user, @NonNull UserProfileChangeRequest request); }
@Test public void testUpdateProfile() { mockVoidResult(true); when(mockFirebaseUser.updateProfile(mockProfileChangeRequest)).thenReturn(mockVoidTaskResult); TestObserver obs = TestObserver.create(); RxFirebaseUser.updateProfile(mockFirebaseUser, mockProfileChangeRequest).subscribe(obs); callOnComplete(mockVoidTaskResult); obs.dispose(); callOnComplete(mockVoidTaskResult); obs.assertNoErrors(); obs.assertComplete(); } @Test public void testUpdateProfile_notSuccessful() { mockNotSuccessfulVoidResult(new IllegalStateException()); when(mockFirebaseUser.updateProfile(mockProfileChangeRequest)).thenReturn(mockVoidTaskResult); TestObserver obs = TestObserver.create(); RxFirebaseUser.updateProfile(mockFirebaseUser, mockProfileChangeRequest).subscribe(obs); callOnComplete(mockVoidTaskResult); obs.dispose(); callOnComplete(mockVoidTaskResult); obs.assertError(IllegalStateException.class); obs.assertNotComplete(); }
RxFirebaseStorage { public static Single<byte[]> getBytes(@NonNull StorageReference ref, final long maxDownloadSizeBytes) { return Single.create(new GetBytesOnSubscribe(ref, maxDownloadSizeBytes)); } private RxFirebaseStorage(); static Single<byte[]> getBytes(@NonNull StorageReference ref, final long maxDownloadSizeBytes); static Completable delete(@NonNull StorageReference ref); static Single<FileDownloadTask.TaskSnapshot> getFile(@NonNull StorageReference ref, @NonNull Uri uri); static Single<FileDownloadTask.TaskSnapshot> getFile(@NonNull StorageReference ref, @NonNull File file); static Single<StorageMetadata> getMetadata(@NonNull StorageReference ref); static Single<StreamDownloadTask.TaskSnapshot> getStream(@NonNull StorageReference ref); static Single<StreamDownloadTask.TaskSnapshot> getStream(@NonNull StorageReference ref, StreamDownloadTask.StreamProcessor streamProcessor); static Single<Uri> getDownloadUrl(@NonNull StorageReference ref); static Single<UploadTask.TaskSnapshot> putBytes(@NonNull StorageReference ref, byte[] bytes); static Single<UploadTask.TaskSnapshot> putBytes(@NonNull StorageReference ref, byte[] bytes, StorageMetadata storageMetadata); static Single<UploadTask.TaskSnapshot> putFile(@NonNull StorageReference ref, @NonNull Uri uri); static Single<UploadTask.TaskSnapshot> putFile(@NonNull StorageReference ref, @NonNull Uri uri, @NonNull StorageMetadata storageMetadata); static Single<UploadTask.TaskSnapshot> putFile(@NonNull StorageReference ref, @NonNull Uri uri, @Nullable StorageMetadata storageMetadata, @Nullable Uri existingUploadUri); static Single<UploadTask.TaskSnapshot> putStream(@NonNull StorageReference ref, @NonNull InputStream inputStream); static Single<UploadTask.TaskSnapshot> putStream(@NonNull StorageReference ref, @NonNull InputStream inputStream, @NonNull StorageMetadata storageMetadata); static Single<StorageMetadata> updateMetadata(@NonNull StorageReference ref, @NonNull StorageMetadata storageMetadata); }
@Test public void testGetBytes() { mockSuccessfulResultForTask(mockBytesTask, new byte[] { 1, 2, 3 }); Mockito.when(mockStorageReference.getBytes(3)).thenReturn(mockBytesTask); TestObserver<byte[]> obs = TestObserver.create(); RxFirebaseStorage.getBytes(mockStorageReference, 3).subscribe(obs); verifyAddOnCompleteListenerForTask(mockBytesTask); callOnComplete(mockBytesTask); obs.dispose(); callOnComplete(mockBytesTask); obs.assertNoErrors(); obs.assertComplete(); obs.assertValue(new Predicate<byte[]>() { @Override public boolean test(byte[] bytes) throws Exception { return Arrays.equals(bytes, new byte[] { 1, 2, 3 }); } }); } @Test public void testGetBytes_notSuccessful() { mockNotSuccessfulResultForTask(mockBytesTask, new IllegalStateException()); when(mockStorageReference.getBytes(3)).thenReturn(mockBytesTask); TestObserver<byte[]> obs = TestObserver.create(); RxFirebaseStorage.getBytes(mockStorageReference, 3).subscribe(obs); verifyAddOnCompleteListenerForTask(mockBytesTask); callOnComplete(mockBytesTask); obs.dispose(); callOnComplete(mockBytesTask); obs.assertError(IllegalStateException.class); obs.assertNoValues(); }
RxFirebaseStorage { public static Completable delete(@NonNull StorageReference ref) { return Completable.create(new DeleteOnSubscribe(ref)); } private RxFirebaseStorage(); static Single<byte[]> getBytes(@NonNull StorageReference ref, final long maxDownloadSizeBytes); static Completable delete(@NonNull StorageReference ref); static Single<FileDownloadTask.TaskSnapshot> getFile(@NonNull StorageReference ref, @NonNull Uri uri); static Single<FileDownloadTask.TaskSnapshot> getFile(@NonNull StorageReference ref, @NonNull File file); static Single<StorageMetadata> getMetadata(@NonNull StorageReference ref); static Single<StreamDownloadTask.TaskSnapshot> getStream(@NonNull StorageReference ref); static Single<StreamDownloadTask.TaskSnapshot> getStream(@NonNull StorageReference ref, StreamDownloadTask.StreamProcessor streamProcessor); static Single<Uri> getDownloadUrl(@NonNull StorageReference ref); static Single<UploadTask.TaskSnapshot> putBytes(@NonNull StorageReference ref, byte[] bytes); static Single<UploadTask.TaskSnapshot> putBytes(@NonNull StorageReference ref, byte[] bytes, StorageMetadata storageMetadata); static Single<UploadTask.TaskSnapshot> putFile(@NonNull StorageReference ref, @NonNull Uri uri); static Single<UploadTask.TaskSnapshot> putFile(@NonNull StorageReference ref, @NonNull Uri uri, @NonNull StorageMetadata storageMetadata); static Single<UploadTask.TaskSnapshot> putFile(@NonNull StorageReference ref, @NonNull Uri uri, @Nullable StorageMetadata storageMetadata, @Nullable Uri existingUploadUri); static Single<UploadTask.TaskSnapshot> putStream(@NonNull StorageReference ref, @NonNull InputStream inputStream); static Single<UploadTask.TaskSnapshot> putStream(@NonNull StorageReference ref, @NonNull InputStream inputStream, @NonNull StorageMetadata storageMetadata); static Single<StorageMetadata> updateMetadata(@NonNull StorageReference ref, @NonNull StorageMetadata storageMetadata); }
@Test public void testDelete() { mockSuccessfulResultForTask(mockTask); Mockito.when(mockStorageReference.delete()).thenReturn(mockTask); TestObserver<byte[]> obs = TestObserver.create(); RxFirebaseStorage.delete(mockStorageReference).subscribe(obs); verifyAddOnCompleteListenerForTask(mockTask); callOnComplete(mockTask); obs.dispose(); callOnComplete(mockTask); obs.assertNoErrors(); obs.assertComplete(); } @Test public void testDelete_notSuccessful() { mockNotSuccessfulResultForTask(mockTask, new IllegalStateException()); when(mockStorageReference.delete()).thenReturn(mockTask); TestObserver obs = TestObserver.create(); RxFirebaseStorage.delete(mockStorageReference).subscribe(obs); verifyAddOnCompleteListenerForTask(mockTask); callOnComplete(mockTask); obs.dispose(); callOnComplete(mockTask); obs.assertError(IllegalStateException.class); obs.assertNoValues(); }
RxFirebaseStorage { public static Single<FileDownloadTask.TaskSnapshot> getFile(@NonNull StorageReference ref, @NonNull Uri uri) { return Single.create(new GetFileToUriOnSubscribe(ref, uri)); } private RxFirebaseStorage(); static Single<byte[]> getBytes(@NonNull StorageReference ref, final long maxDownloadSizeBytes); static Completable delete(@NonNull StorageReference ref); static Single<FileDownloadTask.TaskSnapshot> getFile(@NonNull StorageReference ref, @NonNull Uri uri); static Single<FileDownloadTask.TaskSnapshot> getFile(@NonNull StorageReference ref, @NonNull File file); static Single<StorageMetadata> getMetadata(@NonNull StorageReference ref); static Single<StreamDownloadTask.TaskSnapshot> getStream(@NonNull StorageReference ref); static Single<StreamDownloadTask.TaskSnapshot> getStream(@NonNull StorageReference ref, StreamDownloadTask.StreamProcessor streamProcessor); static Single<Uri> getDownloadUrl(@NonNull StorageReference ref); static Single<UploadTask.TaskSnapshot> putBytes(@NonNull StorageReference ref, byte[] bytes); static Single<UploadTask.TaskSnapshot> putBytes(@NonNull StorageReference ref, byte[] bytes, StorageMetadata storageMetadata); static Single<UploadTask.TaskSnapshot> putFile(@NonNull StorageReference ref, @NonNull Uri uri); static Single<UploadTask.TaskSnapshot> putFile(@NonNull StorageReference ref, @NonNull Uri uri, @NonNull StorageMetadata storageMetadata); static Single<UploadTask.TaskSnapshot> putFile(@NonNull StorageReference ref, @NonNull Uri uri, @Nullable StorageMetadata storageMetadata, @Nullable Uri existingUploadUri); static Single<UploadTask.TaskSnapshot> putStream(@NonNull StorageReference ref, @NonNull InputStream inputStream); static Single<UploadTask.TaskSnapshot> putStream(@NonNull StorageReference ref, @NonNull InputStream inputStream, @NonNull StorageMetadata storageMetadata); static Single<StorageMetadata> updateMetadata(@NonNull StorageReference ref, @NonNull StorageMetadata storageMetadata); }
@SuppressWarnings("Duplicates") @Test public void testGetFileUri() { mockSuccessfulResultForTask(mockFileDownloadTask, mockFileDownloadTaskSnapshot); when(mockStorageReference.getFile(mockUri)).thenReturn(mockFileDownloadTask); when(mockFileDownloadTaskSnapshot.getBytesTransferred()).thenReturn(1000L); when(mockFileDownloadTaskSnapshot.getTotalByteCount()).thenReturn(1000L); TestObserver<FileDownloadTask.TaskSnapshot> obs = TestObserver.create(); RxFirebaseStorage.getFile(mockStorageReference, mockUri).subscribe(obs); verifyAddOnCompleteListenerForTask(mockFileDownloadTask); callOnComplete(mockFileDownloadTask); obs.dispose(); callOnComplete(mockFileDownloadTask); obs.assertNoErrors(); obs.assertComplete(); obs.assertValue(new Predicate<FileDownloadTask.TaskSnapshot>() { @Override public boolean test(FileDownloadTask.TaskSnapshot taskSnapshot) throws Exception { return taskSnapshot.getBytesTransferred() == taskSnapshot.getTotalByteCount() && taskSnapshot.getTotalByteCount() == 1000; } }); } @SuppressWarnings("Duplicates") @Test public void testGetFileUri_notSuccessful() { mockNotSuccessfulResultForTask(mockFileDownloadTask, new IllegalStateException()); when(mockStorageReference.getFile(mockUri)).thenReturn(mockFileDownloadTask); TestObserver<FileDownloadTask.TaskSnapshot> obs = TestObserver.create(); RxFirebaseStorage.getFile(mockStorageReference, mockUri).subscribe(obs); verifyAddOnCompleteListenerForTask(mockFileDownloadTask); callOnComplete(mockFileDownloadTask); obs.dispose(); callOnComplete(mockFileDownloadTask); obs.assertError(IllegalStateException.class); obs.assertNoValues(); } @SuppressWarnings("Duplicates") @Test public void testGetFile() { mockSuccessfulResultForTask(mockFileDownloadTask, mockFileDownloadTaskSnapshot); when(mockStorageReference.getFile(mockFile)).thenReturn(mockFileDownloadTask); when(mockFileDownloadTaskSnapshot.getBytesTransferred()).thenReturn(1000L); when(mockFileDownloadTaskSnapshot.getTotalByteCount()).thenReturn(1000L); TestObserver<FileDownloadTask.TaskSnapshot> obs = TestObserver.create(); RxFirebaseStorage.getFile(mockStorageReference, mockFile).subscribe(obs); verifyAddOnCompleteListenerForTask(mockFileDownloadTask); callOnComplete(mockFileDownloadTask); obs.dispose(); callOnComplete(mockFileDownloadTask); obs.assertNoErrors(); obs.assertComplete(); obs.assertValue(new Predicate<FileDownloadTask.TaskSnapshot>() { @Override public boolean test(FileDownloadTask.TaskSnapshot taskSnapshot) throws Exception { return taskSnapshot.getBytesTransferred() == taskSnapshot.getTotalByteCount() && taskSnapshot.getTotalByteCount() == 1000; } }); } @SuppressWarnings("Duplicates") @Test public void testGetFile_notSuccessful() { mockNotSuccessfulResultForTask(mockFileDownloadTask, new IllegalStateException()); when(mockStorageReference.getFile(mockFile)).thenReturn(mockFileDownloadTask); TestObserver<FileDownloadTask.TaskSnapshot> obs = TestObserver.create(); RxFirebaseStorage.getFile(mockStorageReference, mockFile).subscribe(obs); verifyAddOnCompleteListenerForTask(mockFileDownloadTask); callOnComplete(mockFileDownloadTask); obs.dispose(); callOnComplete(mockFileDownloadTask); obs.assertError(IllegalStateException.class); obs.assertNoValues(); }
RxFirebaseStorage { public static Single<StorageMetadata> getMetadata(@NonNull StorageReference ref) { return Single.create(new GetMetadataOnSubscribe(ref)); } private RxFirebaseStorage(); static Single<byte[]> getBytes(@NonNull StorageReference ref, final long maxDownloadSizeBytes); static Completable delete(@NonNull StorageReference ref); static Single<FileDownloadTask.TaskSnapshot> getFile(@NonNull StorageReference ref, @NonNull Uri uri); static Single<FileDownloadTask.TaskSnapshot> getFile(@NonNull StorageReference ref, @NonNull File file); static Single<StorageMetadata> getMetadata(@NonNull StorageReference ref); static Single<StreamDownloadTask.TaskSnapshot> getStream(@NonNull StorageReference ref); static Single<StreamDownloadTask.TaskSnapshot> getStream(@NonNull StorageReference ref, StreamDownloadTask.StreamProcessor streamProcessor); static Single<Uri> getDownloadUrl(@NonNull StorageReference ref); static Single<UploadTask.TaskSnapshot> putBytes(@NonNull StorageReference ref, byte[] bytes); static Single<UploadTask.TaskSnapshot> putBytes(@NonNull StorageReference ref, byte[] bytes, StorageMetadata storageMetadata); static Single<UploadTask.TaskSnapshot> putFile(@NonNull StorageReference ref, @NonNull Uri uri); static Single<UploadTask.TaskSnapshot> putFile(@NonNull StorageReference ref, @NonNull Uri uri, @NonNull StorageMetadata storageMetadata); static Single<UploadTask.TaskSnapshot> putFile(@NonNull StorageReference ref, @NonNull Uri uri, @Nullable StorageMetadata storageMetadata, @Nullable Uri existingUploadUri); static Single<UploadTask.TaskSnapshot> putStream(@NonNull StorageReference ref, @NonNull InputStream inputStream); static Single<UploadTask.TaskSnapshot> putStream(@NonNull StorageReference ref, @NonNull InputStream inputStream, @NonNull StorageMetadata storageMetadata); static Single<StorageMetadata> updateMetadata(@NonNull StorageReference ref, @NonNull StorageMetadata storageMetadata); }
@Test public void testGetMetadata() { mockSuccessfulResultForTask(mockStorageMetadataTask, mockStorageMetadata); when(mockStorageReference.getMetadata()).thenReturn(mockStorageMetadataTask); when(mockStorageMetadata.getName()).thenReturn("Test"); TestObserver<StorageMetadata> obs = TestObserver.create(); RxFirebaseStorage.getMetadata(mockStorageReference).subscribe(obs); verifyAddOnCompleteListenerForTask(mockStorageMetadataTask); callOnComplete(mockStorageMetadataTask); obs.dispose(); callOnComplete(mockStorageMetadataTask); obs.assertNoErrors(); obs.assertComplete(); obs.assertValue(new Predicate<StorageMetadata>() { @Override public boolean test(StorageMetadata storageMetadata) throws Exception { return "Test".equals(storageMetadata.getName()); } }); } @Test public void testGetMetaData_notSuccessful() { mockNotSuccessfulResultForTask(mockStorageMetadataTask, new IllegalStateException()); when(mockStorageReference.getMetadata()).thenReturn(mockStorageMetadataTask); TestObserver<StorageMetadata> obs = TestObserver.create(); RxFirebaseStorage.getMetadata(mockStorageReference).subscribe(obs); verifyAddOnCompleteListenerForTask(mockStorageMetadataTask); callOnComplete(mockStorageMetadataTask); obs.dispose(); callOnComplete(mockStorageMetadataTask); obs.assertError(IllegalStateException.class); obs.assertNoValues(); }
RxFirebaseStorage { public static Single<StreamDownloadTask.TaskSnapshot> getStream(@NonNull StorageReference ref) { return Single.create(new GetStreamOnSubscribe(ref)); } private RxFirebaseStorage(); static Single<byte[]> getBytes(@NonNull StorageReference ref, final long maxDownloadSizeBytes); static Completable delete(@NonNull StorageReference ref); static Single<FileDownloadTask.TaskSnapshot> getFile(@NonNull StorageReference ref, @NonNull Uri uri); static Single<FileDownloadTask.TaskSnapshot> getFile(@NonNull StorageReference ref, @NonNull File file); static Single<StorageMetadata> getMetadata(@NonNull StorageReference ref); static Single<StreamDownloadTask.TaskSnapshot> getStream(@NonNull StorageReference ref); static Single<StreamDownloadTask.TaskSnapshot> getStream(@NonNull StorageReference ref, StreamDownloadTask.StreamProcessor streamProcessor); static Single<Uri> getDownloadUrl(@NonNull StorageReference ref); static Single<UploadTask.TaskSnapshot> putBytes(@NonNull StorageReference ref, byte[] bytes); static Single<UploadTask.TaskSnapshot> putBytes(@NonNull StorageReference ref, byte[] bytes, StorageMetadata storageMetadata); static Single<UploadTask.TaskSnapshot> putFile(@NonNull StorageReference ref, @NonNull Uri uri); static Single<UploadTask.TaskSnapshot> putFile(@NonNull StorageReference ref, @NonNull Uri uri, @NonNull StorageMetadata storageMetadata); static Single<UploadTask.TaskSnapshot> putFile(@NonNull StorageReference ref, @NonNull Uri uri, @Nullable StorageMetadata storageMetadata, @Nullable Uri existingUploadUri); static Single<UploadTask.TaskSnapshot> putStream(@NonNull StorageReference ref, @NonNull InputStream inputStream); static Single<UploadTask.TaskSnapshot> putStream(@NonNull StorageReference ref, @NonNull InputStream inputStream, @NonNull StorageMetadata storageMetadata); static Single<StorageMetadata> updateMetadata(@NonNull StorageReference ref, @NonNull StorageMetadata storageMetadata); }
@Test public void testGetStream() { mockSuccessfulResultForTask(mockStreamDownloadTask, mockStreamDownloadTaskSnapshot); when(mockStorageReference.getStream()).thenReturn(mockStreamDownloadTask); when(mockStreamDownloadTaskSnapshot.getTotalByteCount()).thenReturn(1000L); when(mockStreamDownloadTaskSnapshot.getBytesTransferred()).thenReturn(1000L); TestObserver<StreamDownloadTask.TaskSnapshot> obs = TestObserver.create(); RxFirebaseStorage.getStream(mockStorageReference).subscribe(obs); verifyAddOnCompleteListenerForTask(mockStreamDownloadTask); callOnComplete(mockStreamDownloadTask); obs.dispose(); callOnComplete(mockStreamDownloadTask); obs.assertNoErrors(); obs.assertComplete(); obs.assertValue(new Predicate<StreamDownloadTask.TaskSnapshot>() { @Override public boolean test(StreamDownloadTask.TaskSnapshot taskSnapshot) throws Exception { return taskSnapshot.getBytesTransferred() == taskSnapshot.getTotalByteCount() && taskSnapshot.getTotalByteCount() == 1000L; } }); } @Test public void testGetStream_notSuccessful() { mockNotSuccessfulResultForTask(mockStreamDownloadTask, new IllegalStateException()); when(mockStorageReference.getStream()).thenReturn(mockStreamDownloadTask); TestObserver<StreamDownloadTask.TaskSnapshot> obs = TestObserver.create(); RxFirebaseStorage.getStream(mockStorageReference).subscribe(obs); verifyAddOnCompleteListenerForTask(mockStreamDownloadTask); callOnComplete(mockStreamDownloadTask); obs.dispose(); callOnComplete(mockStreamDownloadTask); obs.assertError(IllegalStateException.class); obs.assertNoValues(); } @Test public void testGetStreamWithProcessor() { mockSuccessfulResultForTask(mockStreamDownloadTask, mockStreamDownloadTaskSnapshot); when(mockStorageReference.getStream(mockStreamProcessor)).thenReturn(mockStreamDownloadTask); when(mockStreamDownloadTaskSnapshot.getTotalByteCount()).thenReturn(1000L); when(mockStreamDownloadTaskSnapshot.getBytesTransferred()).thenReturn(1000L); TestObserver<StreamDownloadTask.TaskSnapshot> obs = TestObserver.create(); RxFirebaseStorage.getStream(mockStorageReference, mockStreamProcessor).subscribe(obs); verifyAddOnCompleteListenerForTask(mockStreamDownloadTask); callOnComplete(mockStreamDownloadTask); obs.dispose(); callOnComplete(mockStreamDownloadTask); obs.assertNoErrors(); obs.assertComplete(); obs.assertValue(new Predicate<StreamDownloadTask.TaskSnapshot>() { @Override public boolean test(StreamDownloadTask.TaskSnapshot taskSnapshot) throws Exception { return taskSnapshot.getBytesTransferred() == taskSnapshot.getTotalByteCount() && taskSnapshot.getTotalByteCount() == 1000L; } }); } @Test public void testGetStreamWithProcessor_notSuccessful() { mockNotSuccessfulResultForTask(mockStreamDownloadTask, new IllegalStateException()); when(mockStorageReference.getStream(mockStreamProcessor)).thenReturn(mockStreamDownloadTask); TestObserver<StreamDownloadTask.TaskSnapshot> obs = TestObserver.create(); RxFirebaseStorage.getStream(mockStorageReference, mockStreamProcessor).subscribe(obs); verifyAddOnCompleteListenerForTask(mockStreamDownloadTask); callOnComplete(mockStreamDownloadTask); obs.dispose(); callOnComplete(mockStreamDownloadTask); obs.assertError(IllegalStateException.class); obs.assertNoValues(); }
RxFirebaseAuth { @CheckResult @NonNull public static Maybe<FirebaseUser> getCurrentUser( @NonNull final FirebaseAuth instance) { return Maybe.create(new GetCurrentUserOnSubscribe(instance)); } private RxFirebaseAuth(); @CheckResult @NonNull static Observable<FirebaseAuth> authStateChanges( @NonNull FirebaseAuth instance); @CheckResult @NonNull static Single<FirebaseUser> createUserWithEmailAndPassword( @NonNull FirebaseAuth instance, @NonNull String email, @NonNull String password); @CheckResult @NonNull static Maybe<List<String>> fetchProvidersForEmail( @NonNull FirebaseAuth instance, @NonNull String email); @CheckResult @NonNull static Maybe<FirebaseUser> getCurrentUser( @NonNull final FirebaseAuth instance); @CheckResult @NonNull static Completable sendPasswordResetEmail( @NonNull FirebaseAuth instance, @NonNull String email); @CheckResult @NonNull static Single<FirebaseUser> signInAnonymously( @NonNull FirebaseAuth instance); @CheckResult @NonNull static Single<FirebaseUser> signInWithCredential( @NonNull FirebaseAuth instance, @NonNull AuthCredential credential); @CheckResult @NonNull static Single<FirebaseUser> signInWithCustomToken( @NonNull FirebaseAuth instance, @NonNull String token); @CheckResult @NonNull static Single<FirebaseUser> signInWithEmailAndPassword( @NonNull FirebaseAuth instance, @NonNull String email, @NonNull String password); @CheckResult @NonNull static Completable signOut(@NonNull FirebaseAuth instance); @CheckResult @NonNull static Completable applyActionCode(@NonNull FirebaseAuth instance, @NonNull String code); @CheckResult @NonNull static Single<ActionCodeResult> checkActionCode( @NonNull FirebaseAuth instance, @NonNull String code); @CheckResult @NonNull static Completable confirmPasswordReset( @NonNull FirebaseAuth instance, @NonNull String code, @NonNull String newPassword); @CheckResult @NonNull static Single<String> verifyPasswordResetCode( @NonNull FirebaseAuth instance, @NonNull String code); }
@Test public void testGetCurrentUser_notSignedIn() { when(mockFirebaseAuth.getCurrentUser()).thenReturn(null); TestObserver<FirebaseUser> obs = TestObserver.create(); RxFirebaseAuth.getCurrentUser(mockFirebaseAuth).subscribe(obs); verify(mockFirebaseAuth).getCurrentUser(); obs.dispose(); obs.assertNoErrors(); obs.assertComplete(); obs.assertNoValues(); } @Test public void testGetCurrentUser_signedIn() { when(mockFirebaseUser.getDisplayName()).thenReturn("John Doe"); when(mockFirebaseAuth.getCurrentUser()).thenReturn(mockFirebaseUser); TestObserver<FirebaseUser> obs = TestObserver.create(); RxFirebaseAuth.getCurrentUser(mockFirebaseAuth).subscribe(obs); verify(mockFirebaseAuth).getCurrentUser(); obs.dispose(); obs.assertNoErrors(); obs.assertComplete(); obs.assertValue(new Predicate<FirebaseUser>() { @Override public boolean test(FirebaseUser firebaseUser) throws Exception { return "John Doe".equals(firebaseUser.getDisplayName()); } }); }
RxFirebaseStorage { public static Single<Uri> getDownloadUrl(@NonNull StorageReference ref) { return Single.create(new GetDownloadUriOnSubscribe(ref)); } private RxFirebaseStorage(); static Single<byte[]> getBytes(@NonNull StorageReference ref, final long maxDownloadSizeBytes); static Completable delete(@NonNull StorageReference ref); static Single<FileDownloadTask.TaskSnapshot> getFile(@NonNull StorageReference ref, @NonNull Uri uri); static Single<FileDownloadTask.TaskSnapshot> getFile(@NonNull StorageReference ref, @NonNull File file); static Single<StorageMetadata> getMetadata(@NonNull StorageReference ref); static Single<StreamDownloadTask.TaskSnapshot> getStream(@NonNull StorageReference ref); static Single<StreamDownloadTask.TaskSnapshot> getStream(@NonNull StorageReference ref, StreamDownloadTask.StreamProcessor streamProcessor); static Single<Uri> getDownloadUrl(@NonNull StorageReference ref); static Single<UploadTask.TaskSnapshot> putBytes(@NonNull StorageReference ref, byte[] bytes); static Single<UploadTask.TaskSnapshot> putBytes(@NonNull StorageReference ref, byte[] bytes, StorageMetadata storageMetadata); static Single<UploadTask.TaskSnapshot> putFile(@NonNull StorageReference ref, @NonNull Uri uri); static Single<UploadTask.TaskSnapshot> putFile(@NonNull StorageReference ref, @NonNull Uri uri, @NonNull StorageMetadata storageMetadata); static Single<UploadTask.TaskSnapshot> putFile(@NonNull StorageReference ref, @NonNull Uri uri, @Nullable StorageMetadata storageMetadata, @Nullable Uri existingUploadUri); static Single<UploadTask.TaskSnapshot> putStream(@NonNull StorageReference ref, @NonNull InputStream inputStream); static Single<UploadTask.TaskSnapshot> putStream(@NonNull StorageReference ref, @NonNull InputStream inputStream, @NonNull StorageMetadata storageMetadata); static Single<StorageMetadata> updateMetadata(@NonNull StorageReference ref, @NonNull StorageMetadata storageMetadata); }
@Test public void testGetDownloadUrl() { mockSuccessfulResultForTask(mockUriTask, mockUri); when(mockStorageReference.getDownloadUrl()).thenReturn(mockUriTask); when(mockUri.toString()).thenReturn("file: TestObserver<Uri> obs = TestObserver.create(); RxFirebaseStorage.getDownloadUrl(mockStorageReference).subscribe(obs); verifyAddOnCompleteListenerForTask(mockUriTask); callOnComplete(mockUriTask); obs.dispose(); callOnComplete(mockUriTask); obs.assertNoErrors(); obs.assertComplete(); obs.assertValue(new Predicate<Uri>() { @Override public boolean test(Uri uri) throws Exception { return "file: } }); } @Test public void testGetDownloadUrl_notSuccessful() { mockNotSuccessfulResultForTask(mockUriTask, new IllegalStateException()); when(mockStorageReference.getDownloadUrl()).thenReturn(mockUriTask); TestObserver<Uri> obs = TestObserver.create(); RxFirebaseStorage.getDownloadUrl(mockStorageReference).subscribe(obs); verifyAddOnCompleteListenerForTask(mockUriTask); callOnComplete(mockUriTask); obs.dispose(); callOnComplete(mockUriTask); obs.assertError(IllegalStateException.class); obs.assertNoValues(); }
RxFirebaseStorage { public static Single<UploadTask.TaskSnapshot> putBytes(@NonNull StorageReference ref, byte[] bytes) { return Single.create(new PutBytesOnSubscribe(ref, bytes)); } private RxFirebaseStorage(); static Single<byte[]> getBytes(@NonNull StorageReference ref, final long maxDownloadSizeBytes); static Completable delete(@NonNull StorageReference ref); static Single<FileDownloadTask.TaskSnapshot> getFile(@NonNull StorageReference ref, @NonNull Uri uri); static Single<FileDownloadTask.TaskSnapshot> getFile(@NonNull StorageReference ref, @NonNull File file); static Single<StorageMetadata> getMetadata(@NonNull StorageReference ref); static Single<StreamDownloadTask.TaskSnapshot> getStream(@NonNull StorageReference ref); static Single<StreamDownloadTask.TaskSnapshot> getStream(@NonNull StorageReference ref, StreamDownloadTask.StreamProcessor streamProcessor); static Single<Uri> getDownloadUrl(@NonNull StorageReference ref); static Single<UploadTask.TaskSnapshot> putBytes(@NonNull StorageReference ref, byte[] bytes); static Single<UploadTask.TaskSnapshot> putBytes(@NonNull StorageReference ref, byte[] bytes, StorageMetadata storageMetadata); static Single<UploadTask.TaskSnapshot> putFile(@NonNull StorageReference ref, @NonNull Uri uri); static Single<UploadTask.TaskSnapshot> putFile(@NonNull StorageReference ref, @NonNull Uri uri, @NonNull StorageMetadata storageMetadata); static Single<UploadTask.TaskSnapshot> putFile(@NonNull StorageReference ref, @NonNull Uri uri, @Nullable StorageMetadata storageMetadata, @Nullable Uri existingUploadUri); static Single<UploadTask.TaskSnapshot> putStream(@NonNull StorageReference ref, @NonNull InputStream inputStream); static Single<UploadTask.TaskSnapshot> putStream(@NonNull StorageReference ref, @NonNull InputStream inputStream, @NonNull StorageMetadata storageMetadata); static Single<StorageMetadata> updateMetadata(@NonNull StorageReference ref, @NonNull StorageMetadata storageMetadata); }
@Test public void testPutBytes() { mockSuccessfulResultForTask(mockUploadTask, mockUploadTaskSnapshot); when(mockStorageReference.putBytes(new byte[] { 1, 2, 3 })).thenReturn(mockUploadTask); when(mockUploadTaskSnapshot.getBytesTransferred()).thenReturn(1000L); when(mockUploadTaskSnapshot.getTotalByteCount()).thenReturn(1000L); TestObserver<UploadTask.TaskSnapshot> obs = TestObserver.create(); RxFirebaseStorage.putBytes(mockStorageReference, new byte[] { 1, 2, 3 }).subscribe(obs); verifyAddOnCompleteListenerForTask(mockUploadTask); callOnComplete(mockUploadTask); obs.dispose(); callOnComplete(mockUploadTask); obs.assertNoErrors(); obs.assertComplete(); obs.assertValue(new Predicate<UploadTask.TaskSnapshot>() { @Override public boolean test(UploadTask.TaskSnapshot taskSnapshot) throws Exception { return taskSnapshot.getBytesTransferred() == taskSnapshot.getTotalByteCount() && taskSnapshot.getTotalByteCount() == 1000L; } }); } @Test public void testPutBytes_notSuccessful() { mockNotSuccessfulResultForTask(mockUploadTask, new IllegalStateException()); when(mockStorageReference.putBytes(new byte[] { 1, 2, 3 })).thenReturn(mockUploadTask); TestObserver<UploadTask.TaskSnapshot> obs = TestObserver.create(); RxFirebaseStorage.putBytes(mockStorageReference, new byte[] { 1, 2, 3 }).subscribe(obs); verifyAddOnCompleteListenerForTask(mockUploadTask); callOnComplete(mockUploadTask); obs.dispose(); callOnComplete(mockUploadTask); obs.assertError(IllegalStateException.class); obs.assertNoValues(); } @Test public void testPutBytesWithMetadata() { mockSuccessfulResultForTask(mockUploadTask, mockUploadTaskSnapshot); when(mockStorageReference.putBytes(new byte[] { 1, 2, 3 }, mockStorageMetadata)).thenReturn( mockUploadTask); when(mockUploadTaskSnapshot.getBytesTransferred()).thenReturn(1000L); when(mockUploadTaskSnapshot.getTotalByteCount()).thenReturn(1000L); TestObserver<UploadTask.TaskSnapshot> obs = TestObserver.create(); RxFirebaseStorage.putBytes(mockStorageReference, new byte[] { 1, 2, 3 }, mockStorageMetadata) .subscribe(obs); verifyAddOnCompleteListenerForTask(mockUploadTask); callOnComplete(mockUploadTask); obs.dispose(); callOnComplete(mockUploadTask); obs.assertNoErrors(); obs.assertComplete(); obs.assertValue(new Predicate<UploadTask.TaskSnapshot>() { @Override public boolean test(UploadTask.TaskSnapshot taskSnapshot) throws Exception { return taskSnapshot.getBytesTransferred() == taskSnapshot.getTotalByteCount() && taskSnapshot.getTotalByteCount() == 1000L; } }); } @Test public void testPutBytesWithMetadata_notSuccessful() { mockNotSuccessfulResultForTask(mockUploadTask, new IllegalStateException()); when(mockStorageReference.putBytes(new byte[] { 1, 2, 3 }, mockStorageMetadata)).thenReturn( mockUploadTask); TestObserver<UploadTask.TaskSnapshot> obs = TestObserver.create(); RxFirebaseStorage.putBytes(mockStorageReference, new byte[] { 1, 2, 3 }, mockStorageMetadata) .subscribe(obs); verifyAddOnCompleteListenerForTask(mockUploadTask); callOnComplete(mockUploadTask); obs.dispose(); callOnComplete(mockUploadTask); obs.assertError(IllegalStateException.class); obs.assertNoValues(); }
RxFirebaseStorage { public static Single<UploadTask.TaskSnapshot> putFile(@NonNull StorageReference ref, @NonNull Uri uri) { return Single.create(new PutFileOnSubscribe(ref, uri)); } private RxFirebaseStorage(); static Single<byte[]> getBytes(@NonNull StorageReference ref, final long maxDownloadSizeBytes); static Completable delete(@NonNull StorageReference ref); static Single<FileDownloadTask.TaskSnapshot> getFile(@NonNull StorageReference ref, @NonNull Uri uri); static Single<FileDownloadTask.TaskSnapshot> getFile(@NonNull StorageReference ref, @NonNull File file); static Single<StorageMetadata> getMetadata(@NonNull StorageReference ref); static Single<StreamDownloadTask.TaskSnapshot> getStream(@NonNull StorageReference ref); static Single<StreamDownloadTask.TaskSnapshot> getStream(@NonNull StorageReference ref, StreamDownloadTask.StreamProcessor streamProcessor); static Single<Uri> getDownloadUrl(@NonNull StorageReference ref); static Single<UploadTask.TaskSnapshot> putBytes(@NonNull StorageReference ref, byte[] bytes); static Single<UploadTask.TaskSnapshot> putBytes(@NonNull StorageReference ref, byte[] bytes, StorageMetadata storageMetadata); static Single<UploadTask.TaskSnapshot> putFile(@NonNull StorageReference ref, @NonNull Uri uri); static Single<UploadTask.TaskSnapshot> putFile(@NonNull StorageReference ref, @NonNull Uri uri, @NonNull StorageMetadata storageMetadata); static Single<UploadTask.TaskSnapshot> putFile(@NonNull StorageReference ref, @NonNull Uri uri, @Nullable StorageMetadata storageMetadata, @Nullable Uri existingUploadUri); static Single<UploadTask.TaskSnapshot> putStream(@NonNull StorageReference ref, @NonNull InputStream inputStream); static Single<UploadTask.TaskSnapshot> putStream(@NonNull StorageReference ref, @NonNull InputStream inputStream, @NonNull StorageMetadata storageMetadata); static Single<StorageMetadata> updateMetadata(@NonNull StorageReference ref, @NonNull StorageMetadata storageMetadata); }
@Test public void testPutFile() { mockSuccessfulResultForTask(mockUploadTask, mockUploadTaskSnapshot); when(mockStorageReference.putFile(mockUri)).thenReturn(mockUploadTask); when(mockUploadTaskSnapshot.getBytesTransferred()).thenReturn(1000L); when(mockUploadTaskSnapshot.getTotalByteCount()).thenReturn(1000L); TestObserver<UploadTask.TaskSnapshot> obs = TestObserver.create(); RxFirebaseStorage.putFile(mockStorageReference, mockUri).subscribe(obs); verifyAddOnCompleteListenerForTask(mockUploadTask); callOnComplete(mockUploadTask); obs.dispose(); callOnComplete(mockUploadTask); obs.assertNoErrors(); obs.assertComplete(); obs.assertValue(new Predicate<UploadTask.TaskSnapshot>() { @Override public boolean test(UploadTask.TaskSnapshot taskSnapshot) throws Exception { return taskSnapshot.getBytesTransferred() == taskSnapshot.getTotalByteCount() && taskSnapshot.getTotalByteCount() == 1000L; } }); } @Test public void testPutFile_notSuccessful() { mockNotSuccessfulResultForTask(mockUploadTask, new IllegalStateException()); when(mockStorageReference.putFile(mockUri)).thenReturn(mockUploadTask); TestObserver<UploadTask.TaskSnapshot> obs = TestObserver.create(); RxFirebaseStorage.putFile(mockStorageReference, mockUri).subscribe(obs); verifyAddOnCompleteListenerForTask(mockUploadTask); callOnComplete(mockUploadTask); obs.dispose(); callOnComplete(mockUploadTask); obs.assertError(IllegalStateException.class); obs.assertNoValues(); } @Test public void testPutFileWithMetadata() { mockSuccessfulResultForTask(mockUploadTask, mockUploadTaskSnapshot); when(mockStorageReference.putFile(mockUri, mockStorageMetadata)).thenReturn(mockUploadTask); when(mockUploadTaskSnapshot.getBytesTransferred()).thenReturn(1000L); when(mockUploadTaskSnapshot.getTotalByteCount()).thenReturn(1000L); TestObserver<UploadTask.TaskSnapshot> obs = TestObserver.create(); RxFirebaseStorage.putFile(mockStorageReference, mockUri, mockStorageMetadata).subscribe(obs); verifyAddOnCompleteListenerForTask(mockUploadTask); callOnComplete(mockUploadTask); obs.dispose(); callOnComplete(mockUploadTask); obs.assertNoErrors(); obs.assertComplete(); obs.assertValue(new Predicate<UploadTask.TaskSnapshot>() { @Override public boolean test(UploadTask.TaskSnapshot taskSnapshot) throws Exception { return taskSnapshot.getBytesTransferred() == taskSnapshot.getTotalByteCount() && taskSnapshot.getTotalByteCount() == 1000L; } }); } @Test public void testPutFileWithMetadata_notSuccessful() { mockNotSuccessfulResultForTask(mockUploadTask, new IllegalStateException()); when(mockStorageReference.putFile(mockUri, mockStorageMetadata)).thenReturn(mockUploadTask); TestObserver<UploadTask.TaskSnapshot> obs = TestObserver.create(); RxFirebaseStorage.putFile(mockStorageReference, mockUri, mockStorageMetadata).subscribe(obs); verifyAddOnCompleteListenerForTask(mockUploadTask); callOnComplete(mockUploadTask); obs.dispose(); callOnComplete(mockUploadTask); obs.assertError(IllegalStateException.class); obs.assertNoValues(); } @Test public void testPutFileWithMetadataAndUri() { mockSuccessfulResultForTask(mockUploadTask, mockUploadTaskSnapshot); when(mockStorageReference.putFile(mockUri, mockStorageMetadata, mockUri)).thenReturn( mockUploadTask); when(mockUploadTaskSnapshot.getBytesTransferred()).thenReturn(1000L); when(mockUploadTaskSnapshot.getTotalByteCount()).thenReturn(1000L); TestObserver<UploadTask.TaskSnapshot> obs = TestObserver.create(); RxFirebaseStorage.putFile(mockStorageReference, mockUri, mockStorageMetadata, mockUri) .subscribe(obs); verifyAddOnCompleteListenerForTask(mockUploadTask); callOnComplete(mockUploadTask); obs.dispose(); callOnComplete(mockUploadTask); obs.assertNoErrors(); obs.assertComplete(); obs.assertValue(new Predicate<UploadTask.TaskSnapshot>() { @Override public boolean test(UploadTask.TaskSnapshot taskSnapshot) throws Exception { return taskSnapshot.getBytesTransferred() == taskSnapshot.getTotalByteCount() && taskSnapshot.getTotalByteCount() == 1000L; } }); } @Test public void testPutFileWithMetadataAndUri_notSuccessful() { mockNotSuccessfulResultForTask(mockUploadTask, new IllegalStateException()); when(mockStorageReference.putFile(mockUri, mockStorageMetadata, mockUri)).thenReturn( mockUploadTask); TestObserver<UploadTask.TaskSnapshot> obs = TestObserver.create(); RxFirebaseStorage.putFile(mockStorageReference, mockUri, mockStorageMetadata, mockUri) .subscribe(obs); verifyAddOnCompleteListenerForTask(mockUploadTask); callOnComplete(mockUploadTask); obs.dispose(); callOnComplete(mockUploadTask); obs.assertError(IllegalStateException.class); obs.assertNoValues(); }
RxFirebaseStorage { public static Single<UploadTask.TaskSnapshot> putStream(@NonNull StorageReference ref, @NonNull InputStream inputStream) { return Single.create(new PutStreamOnSubscribe(ref, inputStream)); } private RxFirebaseStorage(); static Single<byte[]> getBytes(@NonNull StorageReference ref, final long maxDownloadSizeBytes); static Completable delete(@NonNull StorageReference ref); static Single<FileDownloadTask.TaskSnapshot> getFile(@NonNull StorageReference ref, @NonNull Uri uri); static Single<FileDownloadTask.TaskSnapshot> getFile(@NonNull StorageReference ref, @NonNull File file); static Single<StorageMetadata> getMetadata(@NonNull StorageReference ref); static Single<StreamDownloadTask.TaskSnapshot> getStream(@NonNull StorageReference ref); static Single<StreamDownloadTask.TaskSnapshot> getStream(@NonNull StorageReference ref, StreamDownloadTask.StreamProcessor streamProcessor); static Single<Uri> getDownloadUrl(@NonNull StorageReference ref); static Single<UploadTask.TaskSnapshot> putBytes(@NonNull StorageReference ref, byte[] bytes); static Single<UploadTask.TaskSnapshot> putBytes(@NonNull StorageReference ref, byte[] bytes, StorageMetadata storageMetadata); static Single<UploadTask.TaskSnapshot> putFile(@NonNull StorageReference ref, @NonNull Uri uri); static Single<UploadTask.TaskSnapshot> putFile(@NonNull StorageReference ref, @NonNull Uri uri, @NonNull StorageMetadata storageMetadata); static Single<UploadTask.TaskSnapshot> putFile(@NonNull StorageReference ref, @NonNull Uri uri, @Nullable StorageMetadata storageMetadata, @Nullable Uri existingUploadUri); static Single<UploadTask.TaskSnapshot> putStream(@NonNull StorageReference ref, @NonNull InputStream inputStream); static Single<UploadTask.TaskSnapshot> putStream(@NonNull StorageReference ref, @NonNull InputStream inputStream, @NonNull StorageMetadata storageMetadata); static Single<StorageMetadata> updateMetadata(@NonNull StorageReference ref, @NonNull StorageMetadata storageMetadata); }
@Test public void testPutStream() { mockSuccessfulResultForTask(mockUploadTask, mockUploadTaskSnapshot); when(mockStorageReference.putStream(mockInputStream)).thenReturn(mockUploadTask); when(mockUploadTaskSnapshot.getBytesTransferred()).thenReturn(1000L); when(mockUploadTaskSnapshot.getTotalByteCount()).thenReturn(1000L); TestObserver<UploadTask.TaskSnapshot> obs = TestObserver.create(); RxFirebaseStorage.putStream(mockStorageReference, mockInputStream).subscribe(obs); verifyAddOnCompleteListenerForTask(mockUploadTask); callOnComplete(mockUploadTask); obs.dispose(); callOnComplete(mockUploadTask); obs.assertNoErrors(); obs.assertComplete(); obs.assertValue(new Predicate<UploadTask.TaskSnapshot>() { @Override public boolean test(UploadTask.TaskSnapshot taskSnapshot) throws Exception { return taskSnapshot.getBytesTransferred() == taskSnapshot.getTotalByteCount() && taskSnapshot.getTotalByteCount() == 1000L; } }); } @Test public void testPutStream_notSuccessful() { mockNotSuccessfulResultForTask(mockUploadTask, new IllegalStateException()); when(mockStorageReference.putStream(mockInputStream)).thenReturn(mockUploadTask); TestObserver<UploadTask.TaskSnapshot> obs = TestObserver.create(); RxFirebaseStorage.putStream(mockStorageReference, mockInputStream).subscribe(obs); verifyAddOnCompleteListenerForTask(mockUploadTask); callOnComplete(mockUploadTask); obs.dispose(); callOnComplete(mockUploadTask); obs.assertError(IllegalStateException.class); obs.assertNoValues(); } @Test public void testPutStreamWithMetadata() { mockSuccessfulResultForTask(mockUploadTask, mockUploadTaskSnapshot); when(mockStorageReference.putStream(mockInputStream, mockStorageMetadata)).thenReturn( mockUploadTask); when(mockUploadTaskSnapshot.getBytesTransferred()).thenReturn(1000L); when(mockUploadTaskSnapshot.getTotalByteCount()).thenReturn(1000L); TestObserver<UploadTask.TaskSnapshot> obs = TestObserver.create(); RxFirebaseStorage.putStream(mockStorageReference, mockInputStream, mockStorageMetadata) .subscribe(obs); verifyAddOnCompleteListenerForTask(mockUploadTask); callOnComplete(mockUploadTask); obs.dispose(); callOnComplete(mockUploadTask); obs.assertNoErrors(); obs.assertComplete(); obs.assertValue(new Predicate<UploadTask.TaskSnapshot>() { @Override public boolean test(UploadTask.TaskSnapshot taskSnapshot) throws Exception { return taskSnapshot.getBytesTransferred() == taskSnapshot.getTotalByteCount() && taskSnapshot.getTotalByteCount() == 1000L; } }); } @Test public void testPutStreamWithMetadata_notSuccessful() { mockNotSuccessfulResultForTask(mockUploadTask, new IllegalStateException()); when(mockStorageReference.putStream(mockInputStream, mockStorageMetadata)).thenReturn( mockUploadTask); TestObserver<UploadTask.TaskSnapshot> obs = TestObserver.create(); RxFirebaseStorage.putStream(mockStorageReference, mockInputStream, mockStorageMetadata) .subscribe(obs); verifyAddOnCompleteListenerForTask(mockUploadTask); callOnComplete(mockUploadTask); obs.dispose(); callOnComplete(mockUploadTask); obs.assertError(IllegalStateException.class); obs.assertNoValues(); }
RxFirebaseStorage { public static Single<StorageMetadata> updateMetadata(@NonNull StorageReference ref, @NonNull StorageMetadata storageMetadata) { return Single.create(new UpdateMetadataOnSubscribe(ref, storageMetadata)); } private RxFirebaseStorage(); static Single<byte[]> getBytes(@NonNull StorageReference ref, final long maxDownloadSizeBytes); static Completable delete(@NonNull StorageReference ref); static Single<FileDownloadTask.TaskSnapshot> getFile(@NonNull StorageReference ref, @NonNull Uri uri); static Single<FileDownloadTask.TaskSnapshot> getFile(@NonNull StorageReference ref, @NonNull File file); static Single<StorageMetadata> getMetadata(@NonNull StorageReference ref); static Single<StreamDownloadTask.TaskSnapshot> getStream(@NonNull StorageReference ref); static Single<StreamDownloadTask.TaskSnapshot> getStream(@NonNull StorageReference ref, StreamDownloadTask.StreamProcessor streamProcessor); static Single<Uri> getDownloadUrl(@NonNull StorageReference ref); static Single<UploadTask.TaskSnapshot> putBytes(@NonNull StorageReference ref, byte[] bytes); static Single<UploadTask.TaskSnapshot> putBytes(@NonNull StorageReference ref, byte[] bytes, StorageMetadata storageMetadata); static Single<UploadTask.TaskSnapshot> putFile(@NonNull StorageReference ref, @NonNull Uri uri); static Single<UploadTask.TaskSnapshot> putFile(@NonNull StorageReference ref, @NonNull Uri uri, @NonNull StorageMetadata storageMetadata); static Single<UploadTask.TaskSnapshot> putFile(@NonNull StorageReference ref, @NonNull Uri uri, @Nullable StorageMetadata storageMetadata, @Nullable Uri existingUploadUri); static Single<UploadTask.TaskSnapshot> putStream(@NonNull StorageReference ref, @NonNull InputStream inputStream); static Single<UploadTask.TaskSnapshot> putStream(@NonNull StorageReference ref, @NonNull InputStream inputStream, @NonNull StorageMetadata storageMetadata); static Single<StorageMetadata> updateMetadata(@NonNull StorageReference ref, @NonNull StorageMetadata storageMetadata); }
@Test public void testUpdateMetadata() { when(mockStorageMetadata.getName()).thenReturn("metadata"); mockSuccessfulResultForTask(mockStorageMetadataTask, mockStorageMetadata); TestObserver<StorageMetadata> obs = TestObserver.create(); when(mockStorageReference.updateMetadata(mockStorageMetadata)).thenReturn( mockStorageMetadataTask); RxFirebaseStorage.updateMetadata(mockStorageReference, mockStorageMetadata).subscribe(obs); verifyAddOnCompleteListenerForTask(mockStorageMetadataTask); callOnComplete(mockStorageMetadataTask); obs.dispose(); callOnComplete(mockStorageMetadataTask); obs.assertNoErrors(); obs.assertComplete(); obs.assertValue(new Predicate<StorageMetadata>() { @Override public boolean test(StorageMetadata metadata) throws Exception { return "metadata".equals(metadata.getName()); } }); } @Test public void testUpdateMetadata_notSuccessful() { mockNotSuccessfulResultForTask(mockStorageMetadataTask, new IllegalStateException()); TestObserver<StorageMetadata> obs = TestObserver.create(); when(mockStorageReference.updateMetadata(mockStorageMetadata)).thenReturn( mockStorageMetadataTask); RxFirebaseStorage.updateMetadata(mockStorageReference, mockStorageMetadata).subscribe(obs); verifyAddOnCompleteListenerForTask(mockStorageMetadataTask); callOnComplete(mockStorageMetadataTask); obs.dispose(); callOnComplete(mockStorageMetadataTask); obs.assertError(IllegalStateException.class); obs.assertNoValues(); }
RxFirebaseAuth { @CheckResult @NonNull public static Completable sendPasswordResetEmail( @NonNull FirebaseAuth instance, @NonNull String email) { return Completable.create(new SendPasswordResetEmailOnSubscribe(instance, email)); } private RxFirebaseAuth(); @CheckResult @NonNull static Observable<FirebaseAuth> authStateChanges( @NonNull FirebaseAuth instance); @CheckResult @NonNull static Single<FirebaseUser> createUserWithEmailAndPassword( @NonNull FirebaseAuth instance, @NonNull String email, @NonNull String password); @CheckResult @NonNull static Maybe<List<String>> fetchProvidersForEmail( @NonNull FirebaseAuth instance, @NonNull String email); @CheckResult @NonNull static Maybe<FirebaseUser> getCurrentUser( @NonNull final FirebaseAuth instance); @CheckResult @NonNull static Completable sendPasswordResetEmail( @NonNull FirebaseAuth instance, @NonNull String email); @CheckResult @NonNull static Single<FirebaseUser> signInAnonymously( @NonNull FirebaseAuth instance); @CheckResult @NonNull static Single<FirebaseUser> signInWithCredential( @NonNull FirebaseAuth instance, @NonNull AuthCredential credential); @CheckResult @NonNull static Single<FirebaseUser> signInWithCustomToken( @NonNull FirebaseAuth instance, @NonNull String token); @CheckResult @NonNull static Single<FirebaseUser> signInWithEmailAndPassword( @NonNull FirebaseAuth instance, @NonNull String email, @NonNull String password); @CheckResult @NonNull static Completable signOut(@NonNull FirebaseAuth instance); @CheckResult @NonNull static Completable applyActionCode(@NonNull FirebaseAuth instance, @NonNull String code); @CheckResult @NonNull static Single<ActionCodeResult> checkActionCode( @NonNull FirebaseAuth instance, @NonNull String code); @CheckResult @NonNull static Completable confirmPasswordReset( @NonNull FirebaseAuth instance, @NonNull String code, @NonNull String newPassword); @CheckResult @NonNull static Single<String> verifyPasswordResetCode( @NonNull FirebaseAuth instance, @NonNull String code); }
@Test public void testSendPasswordResetEmail() { when(mockFirebaseAuth.sendPasswordResetEmail("email")).thenReturn( mockSendPasswordResetEmailTask); mockSuccessfulSendPasswordResetEmailResult(); TestObserver obs = TestObserver.create(); RxFirebaseAuth.sendPasswordResetEmail(mockFirebaseAuth, "email").subscribe(obs); callOnComplete(mockSendPasswordResetEmailTask); obs.dispose(); callOnComplete(mockSendPasswordResetEmailTask); verify(mockFirebaseAuth).sendPasswordResetEmail("email"); obs.assertNoErrors(); obs.assertComplete(); } @Test public void testSendPasswordResetEmail_NotSuccessful() { when(mockFirebaseAuth.sendPasswordResetEmail("email")).thenReturn( mockSendPasswordResetEmailTask); mockNotSuccessfulSendPasswordResetEmailResult(new IllegalStateException()); TestObserver obs = TestObserver.create(); RxFirebaseAuth.sendPasswordResetEmail(mockFirebaseAuth, "email").subscribe(obs); callOnComplete(mockSendPasswordResetEmailTask); obs.dispose(); callOnComplete(mockSendPasswordResetEmailTask); verify(mockFirebaseAuth).sendPasswordResetEmail("email"); obs.assertError(IllegalStateException.class); obs.assertNotComplete(); }
RxFirebaseDatabase { @NonNull @CheckResult public static Observable<ChildEvent> childEvents( @NonNull DatabaseReference ref) { return Observable.create(new ChildEventsOnSubscribe(ref)); } private RxFirebaseDatabase(); @NonNull @CheckResult static Observable<ChildEvent> childEvents( @NonNull DatabaseReference ref); @NonNull @CheckResult static Single<DataSnapshot> data(@NonNull DatabaseReference ref); @NonNull @CheckResult static Observable<DataSnapshot> dataChanges( @NonNull DatabaseReference ref); @NonNull @CheckResult static Observable<Optional<T>> dataChangesOf( @NonNull DatabaseReference ref, @NonNull Class<T> clazz); @NonNull @CheckResult static Observable<Optional<T>> dataChangesOf( @NonNull DatabaseReference ref, @NonNull GenericTypeIndicator<T> typeIndicator); @NonNull @CheckResult static Single<Optional<T>> dataOf(@NonNull DatabaseReference ref, @NonNull Class<T> clazz); @NonNull @CheckResult static Single<Optional<T>> dataOf(@NonNull DatabaseReference ref, @NonNull GenericTypeIndicator<T> typeIndicator); @NonNull @CheckResult static Completable removeValue(@NonNull DatabaseReference ref); @NonNull @CheckResult static Completable setPriority(@NonNull DatabaseReference ref, @NonNull Object priority); @NonNull @CheckResult static Completable setValue(@NonNull DatabaseReference ref, @Nullable T value); @NonNull @CheckResult static Completable setValue(@NonNull DatabaseReference ref, @Nullable T value, @NonNull Object priority); @NonNull @CheckResult static Completable runTransaction(@NonNull DatabaseReference ref, @NonNull Function<MutableData, Transaction.Result> task); @NonNull @CheckResult static Completable runTransaction(@NonNull DatabaseReference ref, boolean fireLocalEvents, @NonNull Function<MutableData, Transaction.Result> task); @NonNull @CheckResult static Completable updateChildren(@NonNull DatabaseReference ref, @NonNull Map<String, Object> update); }
@Test public void testChildEvents_add() { TestObserver<ChildEvent> sub = TestObserver.create(); RxFirebaseDatabase.childEvents(mockDatabaseReference).subscribe(sub); verifyAddChildEventListener(); callOnChildAdded("foo"); callOnChildAdded("foo"); sub.assertNotComplete(); sub.assertNoErrors(); sub.assertValueCount(2); List events = sub.getEvents().get(0); for (Object event : events) { assertThat(event).isInstanceOf(ChildEvent.class); assertThat(event).isInstanceOf(ChildAddEvent.class); assertThat(((ChildAddEvent) event).previousChildName()).isEqualTo("foo"); } sub.dispose(); callOnChildAdded("baz"); sub.assertValueCount(2); } @Test public void testChildEvents_change() { TestObserver<ChildEvent> sub = TestObserver.create(); RxFirebaseDatabase.childEvents(mockDatabaseReference).subscribe(sub); verifyAddChildEventListener(); callOnChildChanged("foo"); callOnChildChanged("foo"); sub.assertNotComplete(); sub.assertNoErrors(); sub.assertValueCount(2); List events = sub.getEvents().get(0); for (Object event : events) { assertThat(event).isInstanceOf(ChildEvent.class); assertThat(event).isInstanceOf(ChildChangeEvent.class); assertThat(((ChildChangeEvent) event).previousChildName()).isEqualTo("foo"); } sub.dispose(); callOnChildChanged("foo"); sub.assertValueCount(2); } @Test public void testChildEvents_remove() { TestObserver<ChildEvent> sub = TestObserver.create(); RxFirebaseDatabase.childEvents(mockDatabaseReference).subscribe(sub); verifyAddChildEventListener(); callOnChildRemoved(); callOnChildRemoved(); sub.assertNotComplete(); sub.assertNoErrors(); sub.assertValueCount(2); List events = sub.getEvents().get(0); for (Object event : events) { assertThat(event).isInstanceOf(ChildEvent.class); assertThat(event).isInstanceOf(ChildRemoveEvent.class); } sub.dispose(); callOnChildRemoved(); sub.assertValueCount(2); } @Test public void testChildEvents_move() { TestObserver<ChildEvent> sub = TestObserver.create(); RxFirebaseDatabase.childEvents(mockDatabaseReference).subscribe(sub); verifyAddChildEventListener(); callOnChildMoved("foo"); callOnChildMoved("foo"); sub.assertNotComplete(); sub.assertNoErrors(); sub.assertValueCount(2); List events = sub.getEvents().get(0); for (Object event : events) { assertThat(event).isInstanceOf(ChildEvent.class); assertThat(event).isInstanceOf(ChildMoveEvent.class); assertThat(((ChildMoveEvent) event).previousChildName()).isEqualTo("foo"); } sub.dispose(); callOnChildMoved("foo"); sub.assertValueCount(2); } @Test public void testChildEvents_notSuccessful() { TestObserver<ChildEvent> sub = TestObserver.create(); RxFirebaseDatabase.childEvents(mockDatabaseReference).subscribe(sub); verifyAddChildEventListener(); callChildOnCancelled(); sub.assertNoValues(); assertThat(sub.errorCount()).isEqualTo(1); sub.dispose(); callChildOnCancelled(); assertThat(sub.errorCount()).isEqualTo(1); }
RxFirebaseDatabase { @NonNull @CheckResult public static Single<DataSnapshot> data(@NonNull DatabaseReference ref) { return Single.create(new DataOnSubscribe(ref)); } private RxFirebaseDatabase(); @NonNull @CheckResult static Observable<ChildEvent> childEvents( @NonNull DatabaseReference ref); @NonNull @CheckResult static Single<DataSnapshot> data(@NonNull DatabaseReference ref); @NonNull @CheckResult static Observable<DataSnapshot> dataChanges( @NonNull DatabaseReference ref); @NonNull @CheckResult static Observable<Optional<T>> dataChangesOf( @NonNull DatabaseReference ref, @NonNull Class<T> clazz); @NonNull @CheckResult static Observable<Optional<T>> dataChangesOf( @NonNull DatabaseReference ref, @NonNull GenericTypeIndicator<T> typeIndicator); @NonNull @CheckResult static Single<Optional<T>> dataOf(@NonNull DatabaseReference ref, @NonNull Class<T> clazz); @NonNull @CheckResult static Single<Optional<T>> dataOf(@NonNull DatabaseReference ref, @NonNull GenericTypeIndicator<T> typeIndicator); @NonNull @CheckResult static Completable removeValue(@NonNull DatabaseReference ref); @NonNull @CheckResult static Completable setPriority(@NonNull DatabaseReference ref, @NonNull Object priority); @NonNull @CheckResult static Completable setValue(@NonNull DatabaseReference ref, @Nullable T value); @NonNull @CheckResult static Completable setValue(@NonNull DatabaseReference ref, @Nullable T value, @NonNull Object priority); @NonNull @CheckResult static Completable runTransaction(@NonNull DatabaseReference ref, @NonNull Function<MutableData, Transaction.Result> task); @NonNull @CheckResult static Completable runTransaction(@NonNull DatabaseReference ref, boolean fireLocalEvents, @NonNull Function<MutableData, Transaction.Result> task); @NonNull @CheckResult static Completable updateChildren(@NonNull DatabaseReference ref, @NonNull Map<String, Object> update); }
@Test public void testData() { TestObserver<DataSnapshot> sub = TestObserver.create(); RxFirebaseDatabase.data(mockDatabaseReference).subscribe(sub); verifyAddListenerForSingleValueEvent(); callValueEventOnDataChange("Foo"); sub.dispose(); callValueEventOnDataChange("Foo"); sub.assertNoErrors(); sub.assertComplete(); sub.assertValueCount(1); } @Test public void testData_onCancelled() { TestObserver<DataSnapshot> sub = TestObserver.create(); RxFirebaseDatabase.data(mockDatabaseReference).subscribe(sub); verifyAddListenerForSingleValueEvent(); callValueEventOnCancelled(new DatabaseException("foo")); sub.assertError(DatabaseException.class); sub.assertNoValues(); sub.dispose(); callValueEventOnCancelled(new DatabaseException("foo")); assertThat(sub.errorCount()).isEqualTo(1); }
RxFirebaseDatabase { @NonNull @CheckResult public static Observable<DataSnapshot> dataChanges( @NonNull DatabaseReference ref) { return Observable.create(new DataChangesOnSubscribe(ref)); } private RxFirebaseDatabase(); @NonNull @CheckResult static Observable<ChildEvent> childEvents( @NonNull DatabaseReference ref); @NonNull @CheckResult static Single<DataSnapshot> data(@NonNull DatabaseReference ref); @NonNull @CheckResult static Observable<DataSnapshot> dataChanges( @NonNull DatabaseReference ref); @NonNull @CheckResult static Observable<Optional<T>> dataChangesOf( @NonNull DatabaseReference ref, @NonNull Class<T> clazz); @NonNull @CheckResult static Observable<Optional<T>> dataChangesOf( @NonNull DatabaseReference ref, @NonNull GenericTypeIndicator<T> typeIndicator); @NonNull @CheckResult static Single<Optional<T>> dataOf(@NonNull DatabaseReference ref, @NonNull Class<T> clazz); @NonNull @CheckResult static Single<Optional<T>> dataOf(@NonNull DatabaseReference ref, @NonNull GenericTypeIndicator<T> typeIndicator); @NonNull @CheckResult static Completable removeValue(@NonNull DatabaseReference ref); @NonNull @CheckResult static Completable setPriority(@NonNull DatabaseReference ref, @NonNull Object priority); @NonNull @CheckResult static Completable setValue(@NonNull DatabaseReference ref, @Nullable T value); @NonNull @CheckResult static Completable setValue(@NonNull DatabaseReference ref, @Nullable T value, @NonNull Object priority); @NonNull @CheckResult static Completable runTransaction(@NonNull DatabaseReference ref, @NonNull Function<MutableData, Transaction.Result> task); @NonNull @CheckResult static Completable runTransaction(@NonNull DatabaseReference ref, boolean fireLocalEvents, @NonNull Function<MutableData, Transaction.Result> task); @NonNull @CheckResult static Completable updateChildren(@NonNull DatabaseReference ref, @NonNull Map<String, Object> update); }
@Test public void testDataChanges() { TestObserver<DataSnapshot> sub = TestObserver.create(); RxFirebaseDatabase.dataChanges(mockDatabaseReference).subscribe(sub); verifyAddValueEventListener(); callValueEventOnDataChange("Foo"); sub.assertNotComplete(); sub.assertValueCount(1); sub.dispose(); callValueEventOnDataChange("Foo"); sub.assertValueCount(1); } @Test public void testDataChanges_onCancelled() { TestObserver<DataSnapshot> sub = TestObserver.create(); RxFirebaseDatabase.dataChanges(mockDatabaseReference).subscribe(sub); verifyAddValueEventListener(); callValueEventOnCancelled(new DatabaseException("foo")); sub.assertError(DatabaseException.class); sub.assertNoValues(); sub.dispose(); callValueEventOnCancelled(new DatabaseException("foo")); assertThat(sub.errorCount()).isEqualTo(1); }
RxFirebaseDatabase { @NonNull @CheckResult public static <T> Observable<Optional<T>> dataChangesOf( @NonNull DatabaseReference ref, @NonNull Class<T> clazz) { return dataChanges(ref).compose(new ObsTransformerOfClazz<>(clazz)); } private RxFirebaseDatabase(); @NonNull @CheckResult static Observable<ChildEvent> childEvents( @NonNull DatabaseReference ref); @NonNull @CheckResult static Single<DataSnapshot> data(@NonNull DatabaseReference ref); @NonNull @CheckResult static Observable<DataSnapshot> dataChanges( @NonNull DatabaseReference ref); @NonNull @CheckResult static Observable<Optional<T>> dataChangesOf( @NonNull DatabaseReference ref, @NonNull Class<T> clazz); @NonNull @CheckResult static Observable<Optional<T>> dataChangesOf( @NonNull DatabaseReference ref, @NonNull GenericTypeIndicator<T> typeIndicator); @NonNull @CheckResult static Single<Optional<T>> dataOf(@NonNull DatabaseReference ref, @NonNull Class<T> clazz); @NonNull @CheckResult static Single<Optional<T>> dataOf(@NonNull DatabaseReference ref, @NonNull GenericTypeIndicator<T> typeIndicator); @NonNull @CheckResult static Completable removeValue(@NonNull DatabaseReference ref); @NonNull @CheckResult static Completable setPriority(@NonNull DatabaseReference ref, @NonNull Object priority); @NonNull @CheckResult static Completable setValue(@NonNull DatabaseReference ref, @Nullable T value); @NonNull @CheckResult static Completable setValue(@NonNull DatabaseReference ref, @Nullable T value, @NonNull Object priority); @NonNull @CheckResult static Completable runTransaction(@NonNull DatabaseReference ref, @NonNull Function<MutableData, Transaction.Result> task); @NonNull @CheckResult static Completable runTransaction(@NonNull DatabaseReference ref, boolean fireLocalEvents, @NonNull Function<MutableData, Transaction.Result> task); @NonNull @CheckResult static Completable updateChildren(@NonNull DatabaseReference ref, @NonNull Map<String, Object> update); }
@Test public void testDataChangesOfClazz() { TestObserver<Optional<String>> sub = TestObserver.create(); RxFirebaseDatabase.dataChangesOf(mockDatabaseReference, String.class).subscribe(sub); verifyAddValueEventListener(); callValueEventOnDataChange("Foo"); sub.assertNotComplete(); sub.assertValueCount(1); sub.assertValue(new Predicate<Optional<String>>() { @Override public boolean test(Optional<String> stringOptional) throws Exception { return stringOptional.isPresent() && "Foo".equals(stringOptional.get()); } }); sub.dispose(); callValueEventOnDataChange("Foo"); sub.assertValueCount(1); } @Test public void testDataChangesOfGenericTypeIndicator() { List<String> values = new ArrayList<>(); values.add("Foo"); values.add("Bar"); GenericTypeIndicator<List<String>> typeIndicator = new GenericTypeIndicator<List<String>>() { }; TestObserver<Optional<List<String>>> sub = TestObserver.create(); RxFirebaseDatabase.dataChangesOf(mockDatabaseReference, typeIndicator).subscribe(sub); verifyAddValueEventListener(); callValueEventOnDataChange(typeIndicator, values); sub.assertNotComplete(); sub.assertValue(new Predicate<Optional<List<String>>>() { @Override public boolean test(Optional<List<String>> listOptional) throws Exception { return listOptional.isPresent() && "Foo".equals(listOptional.get().get(0)) && "Bar".equals( listOptional.get().get(1)); } }); sub.dispose(); callValueEventOnDataChange(typeIndicator, values); sub.assertValueCount(1); }
RxFirebaseDatabase { @NonNull @CheckResult public static <T> Single<Optional<T>> dataOf(@NonNull DatabaseReference ref, @NonNull Class<T> clazz) { return data(ref).compose(new SingleTransformerOfClazz<>(clazz)); } private RxFirebaseDatabase(); @NonNull @CheckResult static Observable<ChildEvent> childEvents( @NonNull DatabaseReference ref); @NonNull @CheckResult static Single<DataSnapshot> data(@NonNull DatabaseReference ref); @NonNull @CheckResult static Observable<DataSnapshot> dataChanges( @NonNull DatabaseReference ref); @NonNull @CheckResult static Observable<Optional<T>> dataChangesOf( @NonNull DatabaseReference ref, @NonNull Class<T> clazz); @NonNull @CheckResult static Observable<Optional<T>> dataChangesOf( @NonNull DatabaseReference ref, @NonNull GenericTypeIndicator<T> typeIndicator); @NonNull @CheckResult static Single<Optional<T>> dataOf(@NonNull DatabaseReference ref, @NonNull Class<T> clazz); @NonNull @CheckResult static Single<Optional<T>> dataOf(@NonNull DatabaseReference ref, @NonNull GenericTypeIndicator<T> typeIndicator); @NonNull @CheckResult static Completable removeValue(@NonNull DatabaseReference ref); @NonNull @CheckResult static Completable setPriority(@NonNull DatabaseReference ref, @NonNull Object priority); @NonNull @CheckResult static Completable setValue(@NonNull DatabaseReference ref, @Nullable T value); @NonNull @CheckResult static Completable setValue(@NonNull DatabaseReference ref, @Nullable T value, @NonNull Object priority); @NonNull @CheckResult static Completable runTransaction(@NonNull DatabaseReference ref, @NonNull Function<MutableData, Transaction.Result> task); @NonNull @CheckResult static Completable runTransaction(@NonNull DatabaseReference ref, boolean fireLocalEvents, @NonNull Function<MutableData, Transaction.Result> task); @NonNull @CheckResult static Completable updateChildren(@NonNull DatabaseReference ref, @NonNull Map<String, Object> update); }
@Test public void testDataOfClazz() { TestObserver<Optional<String>> sub = TestObserver.create(); RxFirebaseDatabase.dataOf(mockDatabaseReference, String.class).subscribe(sub); verifyAddListenerForSingleValueEvent(); callValueEventOnDataChange("Foo"); sub.assertComplete(); sub.assertNoErrors(); sub.assertValue(new Predicate<Optional<String>>() { @Override public boolean test(Optional<String> stringOptional) throws Exception { return stringOptional.isPresent() && "Foo".equals(stringOptional.get()); } }); sub.dispose(); callValueEventOnDataChange("Foo"); sub.assertValueCount(1); } @Test public void testDataOfGenericTypeIndicator() { List<String> values = new ArrayList<>(); values.add("Foo"); values.add("Bar"); GenericTypeIndicator<List<String>> typeIndicator = new GenericTypeIndicator<List<String>>() { }; TestObserver<Optional<List<String>>> sub = TestObserver.create(); RxFirebaseDatabase.dataOf(mockDatabaseReference, typeIndicator).subscribe(sub); verifyAddListenerForSingleValueEvent(); callValueEventOnDataChange(typeIndicator, values); sub.assertComplete(); sub.assertNoErrors(); sub.assertValue(new Predicate<Optional<List<String>>>() { @Override public boolean test(Optional<List<String>> listOptional) throws Exception { return listOptional.isPresent() && "Foo".equals(listOptional.get().get(0)) && "Bar".equals( listOptional.get().get(1)); } }); sub.dispose(); callValueEventOnDataChange(typeIndicator, values); sub.assertValueCount(1); }
RxFirebaseDatabase { @NonNull @CheckResult public static Completable removeValue(@NonNull DatabaseReference ref) { return Completable.create(new RemoveValueOnSubscribe(ref)); } private RxFirebaseDatabase(); @NonNull @CheckResult static Observable<ChildEvent> childEvents( @NonNull DatabaseReference ref); @NonNull @CheckResult static Single<DataSnapshot> data(@NonNull DatabaseReference ref); @NonNull @CheckResult static Observable<DataSnapshot> dataChanges( @NonNull DatabaseReference ref); @NonNull @CheckResult static Observable<Optional<T>> dataChangesOf( @NonNull DatabaseReference ref, @NonNull Class<T> clazz); @NonNull @CheckResult static Observable<Optional<T>> dataChangesOf( @NonNull DatabaseReference ref, @NonNull GenericTypeIndicator<T> typeIndicator); @NonNull @CheckResult static Single<Optional<T>> dataOf(@NonNull DatabaseReference ref, @NonNull Class<T> clazz); @NonNull @CheckResult static Single<Optional<T>> dataOf(@NonNull DatabaseReference ref, @NonNull GenericTypeIndicator<T> typeIndicator); @NonNull @CheckResult static Completable removeValue(@NonNull DatabaseReference ref); @NonNull @CheckResult static Completable setPriority(@NonNull DatabaseReference ref, @NonNull Object priority); @NonNull @CheckResult static Completable setValue(@NonNull DatabaseReference ref, @Nullable T value); @NonNull @CheckResult static Completable setValue(@NonNull DatabaseReference ref, @Nullable T value, @NonNull Object priority); @NonNull @CheckResult static Completable runTransaction(@NonNull DatabaseReference ref, @NonNull Function<MutableData, Transaction.Result> task); @NonNull @CheckResult static Completable runTransaction(@NonNull DatabaseReference ref, boolean fireLocalEvents, @NonNull Function<MutableData, Transaction.Result> task); @NonNull @CheckResult static Completable updateChildren(@NonNull DatabaseReference ref, @NonNull Map<String, Object> update); }
@Test public void testRemoveValue() { when(mockDatabaseReference.removeValue()).thenReturn(mockTask); TestObserver sub = TestObserver.create(); RxFirebaseDatabase.removeValue(mockDatabaseReference).subscribe(sub); verifyAddOnCompleteListenerForTask(); callTaskOnComplete(); sub.assertComplete(); sub.assertNoErrors(); sub.dispose(); } @Test public void testRemoveValue_Unsuccessful() { when(mockDatabaseReference.removeValue()).thenReturn(mockTask); TestObserver sub = TestObserver.create(); RxFirebaseDatabase.removeValue(mockDatabaseReference).subscribe(sub); verifyAddOnCompleteListenerForTask(); callTaskOnCompleteWithError(new IllegalStateException()); sub.assertNotComplete(); sub.assertError(IllegalStateException.class); sub.dispose(); }
Index { public static <K, V extends Enum<V>> @NonNull Index<K, V> create(final Class<V> type, final @NonNull Function<? super V, ? extends K> keyFunction) { return create(type, keyFunction, type.getEnumConstants()); } private Index(final Map<K, V> keyToValue, final Map<V, K> valueToKey); static Index<K, V> create(final Class<V> type, final @NonNull Function<? super V, ? extends K> keyFunction); @SafeVarargs static Index<K, V> create(final Class<V> type, final @NonNull Function<? super V, ? extends K> keyFunction, final @NonNull V@NonNull... values); @SafeVarargs @SuppressWarnings("RedundantTypeArguments") // explicit type parameters needed to fix build on JDK 1.8 static Index<K, V> create(final @NonNull Function<? super V, ? extends K> keyFunction, final @NonNull V@NonNull... values); @SuppressWarnings("RedundantTypeArguments") // explicit type parameters needed to fix build on JDK 1.8 static Index<K, V> create(final @NonNull Function<? super V, ? extends K> keyFunction, final @NonNull List<V> constants); @NonNull Set<K> keys(); @Nullable K key(final @NonNull V value); @NonNull Set<V> values(); @Nullable V value(final @NonNull K key); }
@Test void testCreateWithNonUniqueKey() { assertThrows(IllegalStateException.class, () -> Index.create(NonUniqueThing.class, thing -> thing.name)); } @Test void testCreateWithNonUniqueValue() { assertThrows(IllegalStateException.class, () -> Index.create(Thing.class, thing -> UUID.randomUUID().toString(), Thing.ABC, Thing.ABC)); }
AbstractComponent implements Component, Examinable { @Override public final @NonNull Style style() { return this.style; } protected AbstractComponent(final @NonNull List<? extends ComponentLike> children, final @NonNull Style style); @Override final @NonNull List<Component> children(); @Override final @NonNull Style style(); @Override @NonNull Component replaceText(final @NonNull Pattern pattern, final @NonNull Function<TextComponent.Builder, @Nullable ComponentLike> replacement, final @NonNull IntFunction2<PatternReplacementResult> fn); @Override boolean equals(final @Nullable Object other); @Override int hashCode(); @Override @NonNull Stream<? extends ExaminableProperty> examinableProperties(); @Override String toString(); }
@Test void testStyledIfAbsentOnTarget() { final Component c0 = this.builder().color(NamedTextColor.RED).decoration(TextDecoration.STRIKETHROUGH, true).build(); final Component c1 = c0.style(style -> { style.color(NamedTextColor.GREEN); style.decoration(TextDecoration.BOLD, false); }, Style.Merge.Strategy.IF_ABSENT_ON_TARGET); assertEquals(NamedTextColor.GREEN, c1.color()); TextAssertions.assertDecorations(c1, ImmutableSet.of(TextDecoration.STRIKETHROUGH), ImmutableSet.of(TextDecoration.BOLD)); final Component c2 = c0.style(style -> { style.decoration(TextDecoration.BOLD, false); }, Style.Merge.Strategy.IF_ABSENT_ON_TARGET); assertEquals(NamedTextColor.RED, c2.color()); TextAssertions.assertDecorations(c2, ImmutableSet.of(TextDecoration.STRIKETHROUGH), ImmutableSet.of(TextDecoration.BOLD)); } @Test void testResetStyle() { final C c0 = this.builder() .color(NamedTextColor.RED) .decoration(TextDecoration.BOLD, true) .clickEvent(ClickEvent.runCommand("/foo")) .build(); final C c1 = c0.style(Style.empty()); assertNull(c1.color()); TextAssertions.assertDecorations(c1, ImmutableSet.of(), ImmutableSet.of()); assertNull(c1.clickEvent()); assertEquals(c1, c0.color(null).decoration(TextDecoration.BOLD, TextDecoration.State.NOT_SET).clickEvent(null)); } @Test void testSetStyle() { final C c0 = this.buildOne(); assertNull(c0.color()); TextAssertions.assertDecorations(c0, ImmutableSet.of(), ImmutableSet.of()); assertNull(c0.clickEvent()); final C c1 = c0.style(Component.text("xyz", NamedTextColor.RED, ImmutableSet.of(TextDecoration.BOLD)).clickEvent(ClickEvent.runCommand("/foo")).style()); assertEquals(NamedTextColor.RED, c1.color()); TextAssertions.assertDecorations(c1, ImmutableSet.of(TextDecoration.BOLD), ImmutableSet.of()); assertNotNull(c1.clickEvent()); assertEquals(c0, c1.color(null).decoration(TextDecoration.BOLD, TextDecoration.State.NOT_SET).clickEvent(null)); } @Test void testSetStyleOnBuilder() { final B b0 = this.builder(); b0.color(NamedTextColor.RED); final C c0 = b0.build(); b0.style(Style.style(NamedTextColor.GREEN)); final C c1 = b0.build(); assertEquals(NamedTextColor.RED, c0.color()); assertEquals(NamedTextColor.GREEN, c1.color()); } @Test void testStyleConsumer() { final B b0 = this.builder(); b0.style(style -> { style.color(NamedTextColor.RED); }); final C c0 = b0.build(); assertEquals(NamedTextColor.RED, c0.color()); } @Test void testFreshlyBuiltHasEmptyStyle() { final C c0 = this.buildOne(); assertSame(Style.empty(), c0.style()); } @Test void testStyledAlways() { final Component c0 = this.builder().color(NamedTextColor.RED).decoration(TextDecoration.STRIKETHROUGH, true).build(); final Component c1 = c0.style(style -> { style.color(NamedTextColor.GREEN); }); assertEquals(NamedTextColor.GREEN, c1.color()); TextAssertions.assertDecorations(c1, ImmutableSet.of(TextDecoration.STRIKETHROUGH), ImmutableSet.of()); } @Test void testStyledNever() { final Component c0 = this.builder().color(NamedTextColor.RED).decoration(TextDecoration.STRIKETHROUGH, true).build(); final Component c1 = c0.style(style -> { style.color(NamedTextColor.GREEN); }, Style.Merge.Strategy.NEVER); assertEquals(NamedTextColor.GREEN, c1.color()); TextAssertions.assertDecorations(c1, ImmutableSet.of(), ImmutableSet.of()); }
AbstractComponent implements Component, Examinable { @Override public final @NonNull List<Component> children() { return this.children; } protected AbstractComponent(final @NonNull List<? extends ComponentLike> children, final @NonNull Style style); @Override final @NonNull List<Component> children(); @Override final @NonNull Style style(); @Override @NonNull Component replaceText(final @NonNull Pattern pattern, final @NonNull Function<TextComponent.Builder, @Nullable ComponentLike> replacement, final @NonNull IntFunction2<PatternReplacementResult> fn); @Override boolean equals(final @Nullable Object other); @Override int hashCode(); @Override @NonNull Stream<? extends ExaminableProperty> examinableProperties(); @Override String toString(); }
@Test void testRebuildEmptyChildren() { final C c0 = this.buildOne(); final B b0 = c0.toBuilder(); final C c1 = b0.build(); assertEquals(c0, c1); assertThat(c0.children()).isEmpty(); assertThat(c1.children()).isEmpty(); } @Test void testBuilderApplyDeep() { final C c0 = this.builder() .append(Component.text("a", NamedTextColor.RED)) .append(Component.text("b", NamedTextColor.RED)) .applyDeep(builder -> builder.color(NamedTextColor.GREEN)) .build(); final List<Component> children = c0.children(); assertThat(children).hasSize(2); forEachTransformAndAssert(children, Component::color, color -> assertEquals(NamedTextColor.GREEN, color)); } @Test void testChildren() { final C c0 = this.buildOne(); assertThat(c0.children()).isEmpty(); final Component child = Component.text("foo"); final Component c1 = c0.children(Collections.singletonList(child)); assertThat(c1.children()).containsExactly(child).inOrder(); }
LinearComponents { public static @NonNull Component linear(final @NonNull ComponentBuilderApplicable@NonNull... applicables) { final int length = applicables.length; if(length == 0) return Component.empty(); if(length == 1) { final ComponentBuilderApplicable ap0 = applicables[0]; if(ap0 instanceof ComponentLike) { return ((ComponentLike) ap0).asComponent(); } throw nothingComponentLike(); } final TextComponentImpl.BuilderImpl builder = new TextComponentImpl.BuilderImpl(); Style.Builder style = null; for(int i = 0; i < length; i++) { final ComponentBuilderApplicable applicable = applicables[i]; if(applicable instanceof StyleBuilderApplicable) { if(style == null) { style = Style.style(); } style.apply((StyleBuilderApplicable) applicable); } else if(style != null && applicable instanceof ComponentLike) { builder.applicableApply(((ComponentLike) applicable).asComponent().style(style)); } else { builder.applicableApply(applicable); } } final int size = builder.children.size(); if(size == 0) { throw nothingComponentLike(); } else if(size == 1) { return builder.children.get(0); } else { return builder.build(); } } private LinearComponents(); static @NonNull Component linear(final @NonNull ComponentBuilderApplicable@NonNull... applicables); }
@Test void testEmpty() { assertSame(Component.empty(), LinearComponents.linear()); } @Test void testSingleComponentLike() { final Component c0 = Component.text("kittens"); assertSame(c0, LinearComponents.linear(c0)); } @Test void testSimpleText() { final Component c0 = Component.text("kittens", NamedTextColor.DARK_PURPLE); assertEquals(c0, LinearComponents.linear(NamedTextColor.DARK_PURPLE, Component.text().content("kittens"))); } @Test void testAdvancedText() { final Component c0 = Component.text() .append(Component.text("kittens", NamedTextColor.DARK_PURPLE)) .append(Component.text("cats", Style.style(NamedTextColor.DARK_AQUA, TextDecoration.BOLD, HoverEvent.showText(Component.text("are adorable!"))))) .build(); assertEquals(c0, LinearComponents.linear( NamedTextColor.DARK_PURPLE, Component.text().content("kittens"), NamedTextColor.DARK_AQUA, TextDecoration.BOLD, HoverEvent.showText(Component.text("are adorable!")), Component.text().content("cats") )); }
LinearComponents { private static IllegalStateException nothingComponentLike() { return new IllegalStateException("Cannot build component linearly - nothing component-like was given"); } private LinearComponents(); static @NonNull Component linear(final @NonNull ComponentBuilderApplicable@NonNull... applicables); }
@Test void testNothingComponentLike() { assertThrows(IllegalStateException.class, () -> LinearComponents.linear(TextDecoration.BOLD)); assertThrows(IllegalStateException.class, () -> LinearComponents.linear(TextDecoration.BOLD, TextColor.color(0xaa0000))); }
NamedTextColor implements TextColor { public static @NonNull NamedTextColor nearestTo(final @NonNull TextColor any) { if(any instanceof NamedTextColor) { return (NamedTextColor) any; } requireNonNull(any, "color"); int matchedDistance = Integer.MAX_VALUE; NamedTextColor match = VALUES.get(0); for(int i = 0, length = VALUES.size(); i < length; i++) { final NamedTextColor potential = VALUES.get(i); final int distance = distanceSquared(any, potential); if(distance < matchedDistance) { match = potential; matchedDistance = distance; } if(distance == 0) { break; } } return match; } private NamedTextColor(final String name, final int value); static @Nullable NamedTextColor ofExact(final int value); static @NonNull NamedTextColor nearestTo(final @NonNull TextColor any); @Override int value(); @Override @NonNull String toString(); static final NamedTextColor BLACK; static final NamedTextColor DARK_BLUE; static final NamedTextColor DARK_GREEN; static final NamedTextColor DARK_AQUA; static final NamedTextColor DARK_RED; static final NamedTextColor DARK_PURPLE; static final NamedTextColor GOLD; static final NamedTextColor GRAY; static final NamedTextColor DARK_GRAY; static final NamedTextColor BLUE; static final NamedTextColor GREEN; static final NamedTextColor AQUA; static final NamedTextColor RED; static final NamedTextColor LIGHT_PURPLE; static final NamedTextColor YELLOW; static final NamedTextColor WHITE; static final Index<String, NamedTextColor> NAMES; }
@SuppressWarnings("ConstantConditions") @Test void testNullRejected() { assertThrows(NullPointerException.class, () -> NamedTextColor.nearestTo(null), "color"); }
HoverEvent implements Examinable, HoverEventSource<V>, StyleBuilderApplicable { @Override public @NonNull HoverEvent<V> asHoverEvent() { return this; } private HoverEvent(final @NonNull Action<V> action, final @NonNull V value); static @NonNull HoverEvent<Component> showText(final @NonNull Component text); static @NonNull HoverEvent<ShowItem> showItem(final @NonNull Key item, final @NonNegative int count); static @NonNull HoverEvent<ShowItem> showItem(final @NonNull Key item, final @NonNegative int count, final @Nullable BinaryTagHolder nbt); static @NonNull HoverEvent<ShowItem> showItem(final @NonNull ShowItem item); static @NonNull HoverEvent<ShowEntity> showEntity(final @NonNull Key type, final @NonNull UUID id); static @NonNull HoverEvent<ShowEntity> showEntity(final @NonNull Key type, final @NonNull UUID id, final @Nullable Component name); static @NonNull HoverEvent<ShowEntity> showEntity(final @NonNull ShowEntity entity); static HoverEvent<V> hoverEvent(final @NonNull Action<V> action, final @NonNull V value); @Deprecated static HoverEvent<V> of(final @NonNull Action<V> action, final @NonNull V value); @NonNull Action<V> action(); @NonNull V value(); @NonNull HoverEvent<V> value(final @NonNull V value); HoverEvent<V> withRenderedValue(final @NonNull ComponentRenderer<C> renderer, final @NonNull C context); @Override @NonNull HoverEvent<V> asHoverEvent(); @Override @NonNull HoverEvent<V> asHoverEvent(final @NonNull UnaryOperator<V> op); @Override void styleApply(final Style.@NonNull Builder style); @Override boolean equals(final @Nullable Object other); @Override int hashCode(); @Override @NonNull Stream<? extends ExaminableProperty> examinableProperties(); @Override String toString(); }
@Test void testAsHoverEvent() { final HoverEvent<Component> event = HoverEvent.showText(Component.text("kittens")); assertSame(event, event.asHoverEvent()); assertSame(event, event.asHoverEvent(UnaryOperator.identity())); assertEquals(HoverEvent.showText(Component.text("cats")), event.asHoverEvent(old -> Component.text("cats"))); }
HoverEvent implements Examinable, HoverEventSource<V>, StyleBuilderApplicable { @Deprecated public static <V> @NonNull HoverEvent<V> of(final @NonNull Action<V> action, final @NonNull V value) { return new HoverEvent<>(action, value); } private HoverEvent(final @NonNull Action<V> action, final @NonNull V value); static @NonNull HoverEvent<Component> showText(final @NonNull Component text); static @NonNull HoverEvent<ShowItem> showItem(final @NonNull Key item, final @NonNegative int count); static @NonNull HoverEvent<ShowItem> showItem(final @NonNull Key item, final @NonNegative int count, final @Nullable BinaryTagHolder nbt); static @NonNull HoverEvent<ShowItem> showItem(final @NonNull ShowItem item); static @NonNull HoverEvent<ShowEntity> showEntity(final @NonNull Key type, final @NonNull UUID id); static @NonNull HoverEvent<ShowEntity> showEntity(final @NonNull Key type, final @NonNull UUID id, final @Nullable Component name); static @NonNull HoverEvent<ShowEntity> showEntity(final @NonNull ShowEntity entity); static HoverEvent<V> hoverEvent(final @NonNull Action<V> action, final @NonNull V value); @Deprecated static HoverEvent<V> of(final @NonNull Action<V> action, final @NonNull V value); @NonNull Action<V> action(); @NonNull V value(); @NonNull HoverEvent<V> value(final @NonNull V value); HoverEvent<V> withRenderedValue(final @NonNull ComponentRenderer<C> renderer, final @NonNull C context); @Override @NonNull HoverEvent<V> asHoverEvent(); @Override @NonNull HoverEvent<V> asHoverEvent(final @NonNull UnaryOperator<V> op); @Override void styleApply(final Style.@NonNull Builder style); @Override boolean equals(final @Nullable Object other); @Override int hashCode(); @Override @NonNull Stream<? extends ExaminableProperty> examinableProperties(); @Override String toString(); }
@Test void testShowItemItem() { final HoverEvent.ShowItem si0 = HoverEvent.ShowItem.of(Key.key("stone"), 1); assertEquals(Key.key("stone"), si0.item()); final HoverEvent.ShowItem si1 = si0.item(Key.key("dirt")); assertEquals(Key.key("stone"), si0.item()); assertEquals(Key.key("dirt"), si1.item()); } @Test void testShowItemCount() { final HoverEvent.ShowItem si0 = HoverEvent.ShowItem.of(Key.key("stone"), 1); assertEquals(1, si0.count()); assertSame(si0, si0.count(1)); final HoverEvent.ShowItem si1 = si0.count(2); assertEquals(1, si0.count()); assertEquals(2, si1.count()); } @Test void testShowEntityType() { final HoverEvent.ShowEntity se0 = HoverEvent.ShowEntity.of(Key.key("cow"), UUID.randomUUID()); assertEquals(Key.key("cow"), se0.type()); final HoverEvent.ShowEntity se1 = se0.type(Key.key("chicken")); assertEquals(Key.key("cow"), se0.type()); assertEquals(Key.key("chicken"), se1.type()); } @Test void testShowEntityId() { final UUID id0 = UUID.randomUUID(); final HoverEvent.ShowEntity se0 = HoverEvent.ShowEntity.of(Key.key("cow"), id0); assertEquals(id0, se0.id()); final UUID id1 = UUID.randomUUID(); final HoverEvent.ShowEntity se1 = se0.id(id1); assertEquals(id0, se0.id()); assertEquals(id1, se1.id()); } @Test void testShowEntityName() { final Component n0 = Component.text("Cow"); final HoverEvent.ShowEntity se0 = HoverEvent.ShowEntity.of(Key.key("cow"), UUID.randomUUID(), n0); assertEquals(n0, se0.name()); final Component n1 = Component.text("Chicken"); final HoverEvent.ShowEntity se1 = se0.name(n1); assertEquals(n0, se0.name()); assertEquals(n1, se1.name()); } @Test void assertReadable() { for(final HoverEvent.Action<?> action : ImmutableSet.of( HoverEvent.Action.SHOW_TEXT, HoverEvent.Action.SHOW_ITEM, HoverEvent.Action.SHOW_ENTITY )) { assertTrue(action.readable()); } }
Index { public @Nullable K key(final @NonNull V value) { return this.valueToKey.get(value); } private Index(final Map<K, V> keyToValue, final Map<V, K> valueToKey); static Index<K, V> create(final Class<V> type, final @NonNull Function<? super V, ? extends K> keyFunction); @SafeVarargs static Index<K, V> create(final Class<V> type, final @NonNull Function<? super V, ? extends K> keyFunction, final @NonNull V@NonNull... values); @SafeVarargs @SuppressWarnings("RedundantTypeArguments") // explicit type parameters needed to fix build on JDK 1.8 static Index<K, V> create(final @NonNull Function<? super V, ? extends K> keyFunction, final @NonNull V@NonNull... values); @SuppressWarnings("RedundantTypeArguments") // explicit type parameters needed to fix build on JDK 1.8 static Index<K, V> create(final @NonNull Function<? super V, ? extends K> keyFunction, final @NonNull List<V> constants); @NonNull Set<K> keys(); @Nullable K key(final @NonNull V value); @NonNull Set<V> values(); @Nullable V value(final @NonNull K key); }
@Test void testKey() { for(final Thing thing : Thing.values()) { assertEquals(thing.name, THINGS.key(thing)); } }
Index { public @Nullable V value(final @NonNull K key) { return this.keyToValue.get(key); } private Index(final Map<K, V> keyToValue, final Map<V, K> valueToKey); static Index<K, V> create(final Class<V> type, final @NonNull Function<? super V, ? extends K> keyFunction); @SafeVarargs static Index<K, V> create(final Class<V> type, final @NonNull Function<? super V, ? extends K> keyFunction, final @NonNull V@NonNull... values); @SafeVarargs @SuppressWarnings("RedundantTypeArguments") // explicit type parameters needed to fix build on JDK 1.8 static Index<K, V> create(final @NonNull Function<? super V, ? extends K> keyFunction, final @NonNull V@NonNull... values); @SuppressWarnings("RedundantTypeArguments") // explicit type parameters needed to fix build on JDK 1.8 static Index<K, V> create(final @NonNull Function<? super V, ? extends K> keyFunction, final @NonNull List<V> constants); @NonNull Set<K> keys(); @Nullable K key(final @NonNull V value); @NonNull Set<V> values(); @Nullable V value(final @NonNull K key); }
@Test void testValue() { for(final Thing thing : Thing.values()) { assertEquals(thing, THINGS.value(thing.name)); } }
Index { public @NonNull Set<K> keys() { return Collections.unmodifiableSet(this.keyToValue.keySet()); } private Index(final Map<K, V> keyToValue, final Map<V, K> valueToKey); static Index<K, V> create(final Class<V> type, final @NonNull Function<? super V, ? extends K> keyFunction); @SafeVarargs static Index<K, V> create(final Class<V> type, final @NonNull Function<? super V, ? extends K> keyFunction, final @NonNull V@NonNull... values); @SafeVarargs @SuppressWarnings("RedundantTypeArguments") // explicit type parameters needed to fix build on JDK 1.8 static Index<K, V> create(final @NonNull Function<? super V, ? extends K> keyFunction, final @NonNull V@NonNull... values); @SuppressWarnings("RedundantTypeArguments") // explicit type parameters needed to fix build on JDK 1.8 static Index<K, V> create(final @NonNull Function<? super V, ? extends K> keyFunction, final @NonNull List<V> constants); @NonNull Set<K> keys(); @Nullable K key(final @NonNull V value); @NonNull Set<V> values(); @Nullable V value(final @NonNull K key); }
@Test void testKeys() { assertThat(THINGS.keys()).containsExactly("abc", "def"); }
Index { public @NonNull Set<V> values() { return Collections.unmodifiableSet(this.valueToKey.keySet()); } private Index(final Map<K, V> keyToValue, final Map<V, K> valueToKey); static Index<K, V> create(final Class<V> type, final @NonNull Function<? super V, ? extends K> keyFunction); @SafeVarargs static Index<K, V> create(final Class<V> type, final @NonNull Function<? super V, ? extends K> keyFunction, final @NonNull V@NonNull... values); @SafeVarargs @SuppressWarnings("RedundantTypeArguments") // explicit type parameters needed to fix build on JDK 1.8 static Index<K, V> create(final @NonNull Function<? super V, ? extends K> keyFunction, final @NonNull V@NonNull... values); @SuppressWarnings("RedundantTypeArguments") // explicit type parameters needed to fix build on JDK 1.8 static Index<K, V> create(final @NonNull Function<? super V, ? extends K> keyFunction, final @NonNull List<V> constants); @NonNull Set<K> keys(); @Nullable K key(final @NonNull V value); @NonNull Set<V> values(); @Nullable V value(final @NonNull K key); }
@Test void testValues() { assertThat(THINGS.values()).containsExactly(Thing.ABC, Thing.DEF); }
OrdersConnector { public OrderResponse chargeChard() { ResponseEntity<String> orderResponse = request(ordersHost, "/process-order"); return new OrderResponse(orderResponse); } @Autowired OrdersConnector( @Value("${orders.host}") String ordersHost, RestTemplate restTemplate ); OrderResponse chargeChard(); }
@Test public void pingReturnsSuccess_whenSecondTraceSucceeds() throws Exception { doReturn(ResponseEntity.ok().build()).when(restTemplate).getForEntity("http: OrderResponse response = this.subject.chargeChard(); OrderResponse expectedResponse = new OrderResponse(true, "order processed successfully"); assertThat(response, equalTo(expectedResponse)); verify(restTemplate).getForEntity("http: } @Test public void pingReturnsFailure_whenSecondTraceFails() throws Exception { doReturn(ResponseEntity.badRequest().body("invalid content")).when(restTemplate).getForEntity("http: OrderResponse response = this.subject.chargeChard(); OrderResponse expectedResponse = new OrderResponse(false, "unable to process order, please try again."); assertThat(response, equalTo(expectedResponse)); verify(restTemplate).getForEntity("http: }
PaymentsConnector { public PaymentResponse chargeChard() { ResponseEntity<String> paymentResponse = request(paymentsHost, "/charge-card"); return new PaymentResponse(paymentResponse); } @Autowired PaymentsConnector( @Value("${payments.host}") String paymentsHost, RestTemplate restTemplate ); PaymentResponse chargeChard(); }
@Test public void pingReturnsSuccess_whenSecondTraceSucceeds() throws Exception { doReturn(ResponseEntity.ok().build()).when(restTemplate).getForEntity("http: PaymentResponse response = this.subject.chargeChard(); PaymentResponse expectedResponse = new PaymentResponse(true, "order processed successfully"); assertThat(response, equalTo(expectedResponse)); verify(restTemplate).getForEntity("http: } @Test public void pingReturnsFailure_whenSecondTraceFails() throws Exception { doReturn(ResponseEntity.badRequest().body("invalid content")).when(restTemplate).getForEntity("http: PaymentResponse response = this.subject.chargeChard(); PaymentResponse expectedResponse = new PaymentResponse(false, "unable to process order, please try again."); assertThat(response, equalTo(expectedResponse)); verify(restTemplate).getForEntity("http: }
ImageComponent { public static String getWelcomeMap(boolean isSmall) { MapboxStaticImage client = new MapboxStaticImage.Builder() .setAccessToken(Constants.MAPBOX_ACCESS_TOKEN) .setWidth(isSmall ? smallWidth : largeWidth) .setHeight(isSmall ? smallHeight : largeHeight) .setStyleId(com.mapbox.services.Constants.MAPBOX_STYLE_SATELLITE) .setLat(0.0).setLon(0.0) .setZoom(0) .build(); return client.getUrl().toString(); } static String getWelcomeMap(boolean isSmall); static String getLocationMap(Position position, boolean isSmall); static String getRouteMap(Position origin, Position destination, String geometry, boolean isSmall); }
@Test public void getWelcomeMapIsNotEmpty() { assertFalse(TextUtils.isEmpty(ImageComponent.getWelcomeMap(true))); assertTrue(ImageComponent.getWelcomeMap(true).startsWith(BASE_URL)); assertFalse(TextUtils.isEmpty(ImageComponent.getWelcomeMap(false))); assertTrue(ImageComponent.getWelcomeMap(false).startsWith(BASE_URL)); }
ImageComponent { public static String getLocationMap(Position position, boolean isSmall) { StaticMarkerAnnotation marker = new StaticMarkerAnnotation.Builder() .setName(com.mapbox.services.Constants.PIN_LARGE) .setPosition(position) .setColor(COLOR_RED) .build(); MapboxStaticImage client = new MapboxStaticImage.Builder() .setAccessToken(Constants.MAPBOX_ACCESS_TOKEN) .setWidth(isSmall ? smallWidth : largeWidth) .setHeight(isSmall ? smallHeight : largeHeight) .setStyleId(com.mapbox.services.Constants.MAPBOX_STYLE_STREETS) .setPosition(position) .setStaticMarkerAnnotations(marker) .setZoom(15) .build(); return client.getUrl().toString(); } static String getWelcomeMap(boolean isSmall); static String getLocationMap(Position position, boolean isSmall); static String getRouteMap(Position origin, Position destination, String geometry, boolean isSmall); }
@Test public void getLocationMapIsNotEmpty() { Position whiteHouse = Position.fromCoordinates(-77.0365, 38.8977); assertTrue(ImageComponent.getLocationMap(whiteHouse, true).startsWith(BASE_URL)); assertTrue(ImageComponent.getLocationMap(whiteHouse, false).startsWith(BASE_URL)); }
ImageComponent { public static String getRouteMap(Position origin, Position destination, String geometry, boolean isSmall) { StaticMarkerAnnotation markerOrigin = new StaticMarkerAnnotation.Builder() .setName(com.mapbox.services.Constants.PIN_LARGE) .setPosition(origin) .setColor(COLOR_GREEN) .build(); StaticMarkerAnnotation markerDestination = new StaticMarkerAnnotation.Builder() .setName(com.mapbox.services.Constants.PIN_LARGE) .setPosition(destination) .setColor(COLOR_RED) .build(); StaticPolylineAnnotation route = new StaticPolylineAnnotation.Builder() .setPolyline(geometry) .setStrokeColor(COLOR_BLUE) .setStrokeOpacity(1) .setStrokeWidth(5) .build(); MapboxStaticImage client = new MapboxStaticImage.Builder() .setAccessToken(Constants.MAPBOX_ACCESS_TOKEN) .setWidth(isSmall ? smallWidth : largeWidth) .setHeight(isSmall ? smallHeight : largeHeight) .setStyleId(com.mapbox.services.Constants.MAPBOX_STYLE_TRAFFIC_DAY) .setAuto(true) .setStaticMarkerAnnotations(markerOrigin, markerDestination) .setStaticPolylineAnnotations(route) .setZoom(15) .build(); return client.getUrl().toString(); } static String getWelcomeMap(boolean isSmall); static String getLocationMap(Position position, boolean isSmall); static String getRouteMap(Position origin, Position destination, String geometry, boolean isSmall); }
@Test public void getRouteMapIsNotEmpty() { String geometry = "}jllF~_euMm@C?xC}B@?l@e@FItAaAhCaAH?ZqD`BaH@CpCe@f@ye@zTDZ_Bv@"; Position whiteHouse = Position.fromCoordinates(-77.0365, 38.8977); Position dupontCircle = Position.fromCoordinates(-77.04341, 38.90962); assertTrue(ImageComponent.getRouteMap(whiteHouse, dupontCircle, geometry, true).startsWith(BASE_URL)); assertTrue(ImageComponent.getRouteMap(whiteHouse, dupontCircle, geometry, false).startsWith(BASE_URL)); }
OkHttpCall implements Call<T> { @Override public T execute() throws IOException, ApiError { Response response = rawCall.execute(); return adapt(response); } OkHttpCall(okhttp3.Call rawCall, ResponseAdapter<T> adapter); @Override T execute(); @Override void enqueue(final Callback<T> callback); @Override boolean isExecuted(); @Override void cancel(); @Override boolean isCanceled(); @SuppressWarnings("CloneDoesntCallSuperClone") @Override OkHttpCall<T> clone(); }
@Test public void execute_CallsDelegateMethod() throws Exception { testCall.execute(); verify(mockOkHttpCall).execute(); } @Test public void execute_PassesThrownExceptions() throws Exception { IOException error = new IOException(); doThrow(error).when(mockOkHttpCall).execute(); expectedException.expect(is(error)); testCall.execute(); ApiError apiError = new ApiError(5000, ""); doThrow(apiError).when(mockOkHttpCall).execute(); expectedException.expect(is(apiError)); testCall.execute(); }
ExecutorProgressListener implements ProgressListener, Runnable { @Override public void onProgress(long done, long total) { if (!pending || done == total) { this.done = done; this.total = total; try { pending = true; executor.execute(this); } catch (RejectedExecutionException ignored) { pending = false; } } } ExecutorProgressListener(ProgressListener delegate, Executor executor); @Override void run(); @Override void onProgress(long done, long total); }
@Test public void onProgress_Schedules_Once_Until_DelegateGetsNotified() throws Exception { testListener.onProgress(1, 1000); verify(targetExecutor).execute(any(Runnable.class)); testListener.onProgress(2, 1000); verifyNoMoreInteractions(targetExecutor); } @Test public void onProgress_CallsDelegateMethodOnAnotherThread() throws Exception { testListener.onProgress(1, 1000); verifyZeroInteractions(delegateListener); verify(targetExecutor).execute(any(Runnable.class)); }
ScheduledCall implements Call<T> { @Override public T execute() throws IOException, ApiError { return delegate.execute(); } ScheduledCall(Call<T> delegate, Executor callbackExecutor); @Override T execute(); @Override void enqueue(final Callback<T> callback); @Override boolean isExecuted(); @Override void cancel(); @Override boolean isCanceled(); @SuppressWarnings("CloneDoesntCallSuperClone") // Performing deep clone. @Override ScheduledCall<T> clone(); }
@Test public void execute_CallsDelegateMethod() throws Exception { testCall.execute(); verify(wrappedCall).execute(); } @Test public void execute_PassesThrownExceptions() throws Exception { IOException error = new IOException(); doThrow(error).when(wrappedCall).execute(); expectedException.expect(is(error)); testCall.execute(); ApiError apiError = new ApiError(5000, ""); doThrow(apiError).when(wrappedCall).execute(); expectedException.expect(is(apiError)); testCall.execute(); }
ScheduledCall implements Call<T> { @Override public void cancel() { delegate.cancel(); } ScheduledCall(Call<T> delegate, Executor callbackExecutor); @Override T execute(); @Override void enqueue(final Callback<T> callback); @Override boolean isExecuted(); @Override void cancel(); @Override boolean isCanceled(); @SuppressWarnings("CloneDoesntCallSuperClone") // Performing deep clone. @Override ScheduledCall<T> clone(); }
@Test public void cancel_CallsDelegateMethod() throws Exception { testCall.cancel(); verify(wrappedCall).cancel(); }