org.assertj.core.data.Offset Java Examples

The following examples show how to use org.assertj.core.data.Offset. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SimpleLifoPoolTest.java    From reactor-pool with Apache License 2.0 6 votes vote down vote up
@Test
@DisplayName("acquire delays instead of allocating past maxSize")
void acquireDelaysNotAllocate() {
    AtomicInteger newCount = new AtomicInteger();
    SimpleLifoPool<PoolableTest> pool = new SimpleLifoPool<>(poolableTestConfig(2, 3,
            Mono.defer(() -> Mono.just(new PoolableTest(newCount.incrementAndGet())))));

    pool.withPoolable(poolable -> Mono.just(poolable).delayElement(Duration.ofMillis(500))).subscribe();
    pool.withPoolable(poolable -> Mono.just(poolable).delayElement(Duration.ofMillis(500))).subscribe();
    pool.withPoolable(poolable -> Mono.just(poolable).delayElement(Duration.ofMillis(500))).subscribe();

    final Tuple2<Long, PoolableTest> tuple2 = pool.withPoolable(Mono::just).elapsed().blockLast();

    assertThat(tuple2).isNotNull();

    assertThat(tuple2.getT1()).as("pending for 500ms").isCloseTo(500L, Offset.offset(50L));
    assertThat(tuple2.getT2().usedUp).as("discarded twice").isEqualTo(2);
    assertThat(tuple2.getT2().id).as("id").isLessThan(4);
}
 
Example #2
Source File: PeersAwareWeightCalculatorTest.java    From joal with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldProvideExactValues() {
    final PeersAwareWeightCalculator calculator = new PeersAwareWeightCalculator();

    assertThat(calculator.calculate(new Peers(1, 1))).isEqualTo(25);
    assertThat(calculator.calculate(new Peers(2, 1))).isCloseTo(11.1, Offset.offset(0.1));
    assertThat(calculator.calculate(new Peers(30, 1))).isCloseTo(0.104058273, Offset.offset(0.00000001));
    assertThat(calculator.calculate(new Peers(0, 1))).isEqualTo(0);
    assertThat(calculator.calculate(new Peers(1, 0))).isEqualTo(0);
    assertThat(calculator.calculate(new Peers(2, 100))).isCloseTo(9611.687812, Offset.offset(0.0001));
    assertThat(calculator.calculate(new Peers(0, 100))).isEqualTo(0);
    assertThat(calculator.calculate(new Peers(2000, 150))).isEqualTo(73.01243916, Offset.offset(0.00001));
    assertThat(calculator.calculate(new Peers(150, 2000))).isCloseTo(173066.5224, Offset.offset(0.01));
    assertThat(calculator.calculate(new Peers(80, 2000))).isCloseTo(184911.2426, Offset.offset(0.1));
    assertThat(calculator.calculate(new Peers(2000, 2000))).isEqualTo(50000);
    assertThat(calculator.calculate(new Peers(0, 0))).isEqualTo(0);
}
 
Example #3
Source File: S3PresignerTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void getObject_Sigv4PresignerHonorsSignatureDuration() {
    AwsRequestOverrideConfiguration override =
        AwsRequestOverrideConfiguration.builder()
                                       .signer(AwsS3V4Signer.create())
                                       .build();

    PresignedGetObjectRequest presigned =
        presigner.presignGetObject(r -> r.signatureDuration(Duration.ofSeconds(1234))
                                         .getObjectRequest(gor -> gor.bucket("a")
                                                                     .key("b")
                                                                     .overrideConfiguration(override)));

    assertThat(presigned.httpRequest().rawQueryParameters().get("X-Amz-Expires").get(0)).satisfies(expires -> {
        assertThat(expires).containsOnlyDigits();
        assertThat(Integer.parseInt(expires)).isCloseTo(1234, Offset.offset(2));
    });
}
 
Example #4
Source File: S3PresignerTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void putObject_Sigv4PresignerHonorsSignatureDuration() {
    AwsRequestOverrideConfiguration override =
        AwsRequestOverrideConfiguration.builder()
                                       .signer(AwsS3V4Signer.create())
                                       .build();

    PresignedPutObjectRequest presigned =
        presigner.presignPutObject(r -> r.signatureDuration(Duration.ofSeconds(1234))
                                         .putObjectRequest(gor -> gor.bucket("a")
                                                                     .key("b")
                                                                     .overrideConfiguration(override)));

    assertThat(presigned.httpRequest().rawQueryParameters().get("X-Amz-Expires").get(0)).satisfies(expires -> {
        assertThat(expires).containsOnlyDigits();
        assertThat(Integer.parseInt(expires)).isCloseTo(1234, Offset.offset(2));
    });
}
 
Example #5
Source File: IndexLengthRestrictionEnforcerTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void enforceRestrictionsOnViolation() {
    // GIVEN:
    final String key = "/attributes/enforceRestrictionsOnViolation";
    final int maxAllowedValueForKey = MAX_INDEX_CONTENT_LENGTH - OVERHEAD - key.length();
    final String value = TestStringGenerator.createStringOfBytes(maxAllowedValueForKey + 1);

    // WHEN:
    final String enforcedValue = indexLengthRestrictionEnforcer.enforce(JsonPointer.of(key), JsonValue.of(value))
            .orElseThrow()
            .asString();
    final int enforcedValueBytes = enforcedValue.getBytes(StandardCharsets.UTF_8).length;

    // THEN: value is truncated to fit in the max allowed value bytes
    assertThat(value).startsWith(enforcedValue);
    assertThat(enforcedValueBytes).isLessThanOrEqualTo(maxAllowedValueForKey);

    // THEN: value is not truncated more than needed
    final int maxUtf8Bytes = 4;
    assertThat(enforcedValueBytes).isCloseTo(maxAllowedValueForKey, Offset.offset(maxUtf8Bytes));
}
 
Example #6
Source File: SpanTest.java    From wingtips with Apache License 2.0 6 votes vote down vote up
public static void verifySpanDeepEquals(
    Span spanToVerify, Span expectedSpan, boolean allowStartTimeNanosFudgeFactor
) {
    assertThat(spanToVerify.getSpanStartTimeEpochMicros()).isEqualTo(expectedSpan.getSpanStartTimeEpochMicros());
    if (allowStartTimeNanosFudgeFactor) {
        assertThat(spanToVerify.getSpanStartTimeNanos())
            .isCloseTo(expectedSpan.getSpanStartTimeNanos(), Offset.offset(TimeUnit.MILLISECONDS.toNanos(1)));
    }
    else {
        assertThat(spanToVerify.getSpanStartTimeNanos()).isEqualTo(expectedSpan.getSpanStartTimeNanos());
    }
    assertThat(spanToVerify.isCompleted()).isEqualTo(expectedSpan.isCompleted());
    assertThat(spanToVerify.getTraceId()).isEqualTo(expectedSpan.getTraceId());
    assertThat(spanToVerify.getSpanId()).isEqualTo(expectedSpan.getSpanId());
    assertThat(spanToVerify.getParentSpanId()).isEqualTo(expectedSpan.getParentSpanId());
    assertThat(spanToVerify.getSpanName()).isEqualTo(expectedSpan.getSpanName());
    assertThat(spanToVerify.isSampleable()).isEqualTo(expectedSpan.isSampleable());
    assertThat(spanToVerify.getUserId()).isEqualTo(expectedSpan.getUserId());
    assertThat(spanToVerify.getDurationNanos()).isEqualTo(expectedSpan.getDurationNanos());
    assertThat(spanToVerify.getSpanPurpose()).isEqualTo(expectedSpan.getSpanPurpose());
    assertThat(spanToVerify.getTags()).isEqualTo(expectedSpan.getTags());
    assertThat(spanToVerify.getTimestampedAnnotations()).isEqualTo(expectedSpan.getTimestampedAnnotations());
}
 
Example #7
Source File: SimpleStreamSenderIT.java    From quilt with Apache License 2.0 6 votes vote down vote up
private SendMoneyResult sendMoneyWithConfiguredSleep(Duration sleepTimeDuration, int streamConnectionId) {
  final UnsignedLong paymentAmount = UnsignedLong.valueOf(100000);

  StreamSender heavySleeperSender = new SimpleStreamSender(link, sleepTimeDuration);

  final StreamConnectionDetails connectionDetails = getStreamConnectionDetails(streamConnectionId);

  final SendMoneyResult heavySleeperResult = heavySleeperSender.sendMoney(
      SendMoneyRequest.builder()
          .sourceAddress(SENDER_ADDRESS)
          .amount(paymentAmount)
          .denomination(Denominations.XRP_DROPS)
          .destinationAddress(connectionDetails.destinationAddress())
          .sharedSecret(connectionDetails.sharedSecret())
          .paymentTracker(new FixedSenderAmountPaymentTracker(paymentAmount, new NoOpExchangeRateCalculator()))
          .build()
  ).join();

  assertThat(heavySleeperResult.amountDelivered()).isEqualTo(paymentAmount);
  assertThat(heavySleeperResult.originalAmount()).isEqualTo(paymentAmount);
  assertThat(heavySleeperResult.numFulfilledPackets()).isCloseTo(8, Offset.offset(1));
  assertThat(heavySleeperResult.numRejectPackets()).isEqualTo(0);

  logger.info("Payment Sent via sender with sleep = {} : {}", sleepTimeDuration.toMillis(), heavySleeperResult);
  return heavySleeperResult;
}
 
Example #8
Source File: SchedulerTest.java    From Wisp with Apache License 2.0 6 votes vote down vote up
@Test
public void check_that_metrics_are_correctly_updated_during_and_after_a_job_execution() throws InterruptedException {
	Scheduler scheduler = new Scheduler();

	Job job = scheduler.schedule(Utils.TASK_THAT_SLEEPS_FOR_200MS, Schedules.fixedDelaySchedule(Duration.ofMillis(1)));

	Thread.sleep(25L);
	assertThat(job.executionsCount()).isZero();
	assertThat(job.lastExecutionEndedTimeInMillis()).isNull();
	assertThat(job.lastExecutionStartedTimeInMillis()).isCloseTo(System.currentTimeMillis(), Offset.offset(200L));
	assertThat(job.threadRunningJob()).isNotNull();

	scheduler.gracefullyShutdown();

	assertThat(job.executionsCount()).isOne();
	assertThat(job.lastExecutionEndedTimeInMillis()).isNotNull();
	assertThat(job.lastExecutionStartedTimeInMillis()).isNotNull();
	assertThat(job.threadRunningJob()).isNull();
}
 
Example #9
Source File: MathUtilTest.java    From NOVA-Core with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void testLerp() {
	Offset<Double> offsetD = Offset.offset(1e-11);
	Offset<Float> offsetF = Offset.offset(1e-7F);
	assertThat(MathUtil.lerp(1D, 2D, 0)).isCloseTo(1, offsetD);
	assertThat(MathUtil.lerp(1D, 2D, .5)).isCloseTo(1.5, offsetD);
	assertThat(MathUtil.lerp(1D, 2D, 1)).isCloseTo(2, offsetD);

	assertThat(MathUtil.lerp(1F, 2F, 0F)).isCloseTo(1F, offsetF);
	assertThat(MathUtil.lerp(1F, 2F, .5F)).isCloseTo(1.5F, offsetF);
	assertThat(MathUtil.lerp(1F, 2F, 1F)).isCloseTo(2F, offsetF);

	assertThat(MathUtil.lerp(Vector3D.ZERO, Vector3DUtil.ONE, 0)).isAlmostEqualTo(Vector3D.ZERO);
	assertThat(MathUtil.lerp(Vector3D.ZERO, Vector3DUtil.ONE, .5F)).isAlmostEqualTo(Vector3DUtil.ONE.scalarMultiply(0.5));
	assertThat(MathUtil.lerp(Vector3D.ZERO, Vector3DUtil.ONE, 1)).isAlmostEqualTo(Vector3DUtil.ONE);
}
 
Example #10
Source File: MonoRunnableTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void runnableSubscribeToCompleteMeasurement() {
	AtomicLong subscribeTs = new AtomicLong();
	Mono<Object> mono = Mono.fromRunnable(() -> {
		try {
			Thread.sleep(500);
		}
		catch (InterruptedException e) {
			e.printStackTrace();
		}
	})
	                      .doOnSubscribe(sub -> subscribeTs.set(-1 * System.nanoTime()))
	                      .doFinally(fin -> subscribeTs.addAndGet(System.nanoTime()));

	StepVerifier.create(mono)
	            .verifyComplete();

	assertThat(TimeUnit.NANOSECONDS.toMillis(subscribeTs.get())).isCloseTo(500L, Offset.offset(50L));
}
 
Example #11
Source File: MonoCallableTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void callableSubscribeToCompleteMeasurement() {
    AtomicLong subscribeTs = new AtomicLong();
    Mono<String> mono = Mono.fromCallable(() -> {
        try {
            Thread.sleep(500);
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "foo";
    })
                            .doOnSubscribe(sub -> subscribeTs.set(-1 * System.nanoTime()))
                            .doFinally(fin -> subscribeTs.addAndGet(System.nanoTime()));

    StepVerifier.create(mono)
                .expectNext("foo")
                .verifyComplete();

    assertThat(TimeUnit.NANOSECONDS.toMillis(subscribeTs.get())).isCloseTo(500L, Offset.offset(50L));
}
 
Example #12
Source File: BuyerSteps.java    From serenity-documentation with Apache License 2.0 6 votes vote down vote up
@Step
public void should_see_total_including_shipping_for(ListingItem selectedItem) {
    OrderCostSummary orderCostSummary
            = cartPage.getOrderCostSummaryFor(selectedItem).get();

    double itemTotal = orderCostSummary.getItemTotal();
    double shipping = orderCostSummary.getShipping();
    double totalCost = orderCostSummary.getTotalCost();

    assertThat(itemTotal).isEqualTo(selectedItem.getPrice());

    if (cartPage.isShowingShippingCosts()) {
        assertThat(shipping).isGreaterThan(0.0);
        assertThat(totalCost).isCloseTo(itemTotal + shipping, Offset.offset(0.001));
    }
}
 
Example #13
Source File: SimpleFifoPoolTest.java    From reactor-pool with Apache License 2.0 6 votes vote down vote up
@Test
@DisplayName("acquire delays instead of allocating past maxSize")
void acquireDelaysNotAllocate() {
    AtomicInteger newCount = new AtomicInteger();
    SimpleFifoPool<PoolableTest> pool = new SimpleFifoPool<>(poolableTestConfig(2, 3,
            Mono.defer(() -> Mono.just(new PoolableTest(newCount.incrementAndGet())))));

    pool.withPoolable(poolable -> Mono.just(poolable).delayElement(Duration.ofMillis(500))).subscribe();
    pool.withPoolable(poolable -> Mono.just(poolable).delayElement(Duration.ofMillis(500))).subscribe();
    pool.withPoolable(poolable -> Mono.just(poolable).delayElement(Duration.ofMillis(500))).subscribe();

    final Tuple2<Long, PoolableTest> tuple2 = pool.withPoolable(Mono::just).elapsed().blockLast();

    assertThat(tuple2).isNotNull();

    assertThat(tuple2.getT1()).as("pending for 500ms").isCloseTo(500L, Offset.offset(50L));
    assertThat(tuple2.getT2().usedUp).as("discarded twice").isEqualTo(2);
    assertThat(tuple2.getT2().id).as("id").isLessThan(4);
}
 
Example #14
Source File: MultiRedisLockTest.java    From distributed-lock with MIT License 6 votes vote down vote up
@Test
public void shouldNotRefreshBecauseTokenForOneKeyDoesNotMatch() {
  final var keys = Arrays.asList("1", "2");

  final var token = lock.acquire(keys, "locks", 1000);
  assertThat(redisTemplate.getExpire("locks:1", TimeUnit.MILLISECONDS)).isCloseTo(1000, Offset.offset(100L));
  assertThat(redisTemplate.getExpire("locks:2", TimeUnit.MILLISECONDS)).isCloseTo(1000, Offset.offset(100L));

  redisTemplate.opsForValue().set("locks:1", "wrong-token");

  assertThat(lock.refresh(keys, "locks", token, 1000)).isFalse();
  assertThat(redisTemplate.getExpire("locks:1", TimeUnit.MILLISECONDS)).isEqualTo(-1L); // expiration was removed on manual update in this test
  assertThat(redisTemplate.getExpire("locks:2", TimeUnit.MILLISECONDS)).isCloseTo(1000, Offset.offset(100L));
  assertThat(redisTemplate.opsForValue().get("locks:1")).isEqualTo("wrong-token");
  assertThat(redisTemplate.opsForValue().get("locks:2")).isEqualTo(token);
}
 
Example #15
Source File: FluentEqualityConfig.java    From curiostack with MIT License 5 votes vote down vote up
final FluentEqualityConfig usingDoubleToleranceForFields(
    double tolerance, Iterable<Integer> fieldNumbers) {
  return toBuilder()
      .setDoubleCorrespondenceMap(
          doubleCorrespondenceMap()
              .with(
                  FieldScopeLogic.none().allowingFieldsNonRecursive(fieldNumbers),
                  Offset.strictOffset(tolerance)))
      .addUsingCorrespondenceFieldNumbersString(
          ".usingDoubleTolerance(" + tolerance + ", %s)", fieldNumbers)
      .build();
}
 
Example #16
Source File: ProtoTruthMessageDifferencer.java    From curiostack with MIT License 5 votes vote down vote up
private static boolean doublesEqual(double x, double y, Optional<Offset<Double>> correspondence) {
  if (correspondence.isPresent()) {
    try {
      assertThat(x).isCloseTo(y, correspondence.get());
    } catch (AssertionError e) {
      return false;
    }
    return true;
  } else {
    return Double.compare(x, y) == 0;
  }
}
 
Example #17
Source File: ProtoTruthMessageDifferencer.java    From curiostack with MIT License 5 votes vote down vote up
private static boolean floatsEqual(float x, float y, Optional<Offset<Float>> correspondence) {
  if (correspondence.isPresent()) {
    try {
      assertThat(x).isCloseTo(y, correspondence.get());
    } catch (AssertionError e) {
      return false;
    }
    return true;
  } else {
    return Float.compare(x, y) == 0;
  }
}
 
Example #18
Source File: CommonPoolTest.java    From reactor-pool with Apache License 2.0 5 votes vote down vote up
@ParameterizedTest
@MethodSource("allPools")
@Tag("metrics")
void recordsResetLatencies(Function<PoolBuilder<String, ?>, AbstractPool<String>> configAdjuster) {
	AtomicBoolean flip = new AtomicBoolean();
	//note the starter method here is irrelevant, only the config is created and passed to createPool
	PoolBuilder<String, ?> builder = PoolBuilder
			.from(Mono.just("foo"))
			.releaseHandler(s -> {
				if (flip.compareAndSet(false,
						true)) {
					return Mono.delay(Duration.ofMillis(
							100))
					           .then();
				}
				else {
					flip.compareAndSet(true,
							false);
					return Mono.empty();
				}
			})
			.metricsRecorder(recorder)
			.clock(recorder);
	Pool<String> pool = configAdjuster.apply(builder);

	pool.acquire().flatMap(PooledRef::release).block();
	pool.acquire().flatMap(PooledRef::release).block();

	assertThat(recorder.getResetCount()).as("reset").isEqualTo(2);

	long min = recorder.getResetHistogram().getMinValue();
	assertThat(min).isCloseTo(0L, Offset.offset(50L));

	long max = recorder.getResetHistogram().getMaxValue();
	assertThat(max).isCloseTo(100L, Offset.offset(50L));
}
 
Example #19
Source File: SimpleStreamSenderIT.java    From quilt with Apache License 2.0 5 votes vote down vote up
/**
 * One call to {@link SimpleStreamSender#sendMoney(SendMoneyRequest)}} that involves multiple packets in parallel.
 */
@Test
public void sendMoneyMultiPacket() {
  final UnsignedLong paymentAmount = UnsignedLong.valueOf(100000);

  StreamSender streamSender = new SimpleStreamSender(link);

  final StreamConnectionDetails connectionDetails = getStreamConnectionDetails(1000001);

  final SendMoneyResult sendMoneyResult = streamSender.sendMoney(
      SendMoneyRequest.builder()
          .sourceAddress(SENDER_ADDRESS)
          .amount(paymentAmount)
          .denomination(Denominations.XRP_DROPS)
          .destinationAddress(connectionDetails.destinationAddress())
          .sharedSecret(connectionDetails.sharedSecret())
          .paymentTracker(new FixedSenderAmountPaymentTracker(paymentAmount, new NoOpExchangeRateCalculator()))
          .build()
  ).join();

  assertThat(sendMoneyResult.amountDelivered()).isEqualTo(paymentAmount);
  assertThat(sendMoneyResult.originalAmount()).isEqualTo(paymentAmount);
  assertThat(sendMoneyResult.numFulfilledPackets()).isCloseTo(8, Offset.offset(1));
  assertThat(sendMoneyResult.numRejectPackets()).isEqualTo(0);

  logger.info("Payment Sent: {}", sendMoneyResult);
}
 
Example #20
Source File: SimpleRedisLockTest.java    From distributed-lock with MIT License 5 votes vote down vote up
@Test
public void shouldRefresh() throws InterruptedException {
  final String token = lock.acquire(Collections.singletonList("1"), "locks", 1000);
  assertThat(redisTemplate.getExpire("locks:1", TimeUnit.MILLISECONDS)).isCloseTo(1000, Offset.offset(100L));
  Thread.sleep(500);
  assertThat(redisTemplate.getExpire("locks:1", TimeUnit.MILLISECONDS)).isCloseTo(500, Offset.offset(100L));
  assertThat(lock.refresh(Collections.singletonList("1"), "locks", token, 1000)).isTrue();
  assertThat(redisTemplate.getExpire("locks:1", TimeUnit.MILLISECONDS)).isCloseTo(1000, Offset.offset(100L));
}
 
Example #21
Source File: CommonPoolTest.java    From reactor-pool with Apache License 2.0 5 votes vote down vote up
@ParameterizedTest
@MethodSource("allPools")
@Tag("metrics")
void recordsLifetime(Function<PoolBuilder<Integer, ?>, AbstractPool<Integer>> configAdjuster) throws InterruptedException {
	AtomicInteger allocCounter = new AtomicInteger();
	AtomicInteger destroyCounter = new AtomicInteger();
	//note the starter method here is irrelevant, only the config is created and passed to createPool
	PoolBuilder<Integer, ?> builder = PoolBuilder
			.from(Mono.fromCallable(allocCounter::incrementAndGet))
			.sizeBetween(0, 2)
			.evictionPredicate((poolable, metadata) -> metadata.acquireCount() >= 2)
			.destroyHandler(i -> Mono.fromRunnable(destroyCounter::incrementAndGet))
			.metricsRecorder(recorder)
			.clock(recorder);
	Pool<Integer> pool = configAdjuster.apply(builder);

	//first round
	PooledRef<Integer> ref1 = pool.acquire().block();
	PooledRef<Integer> ref2 = pool.acquire().block();
	Thread.sleep(250);
	ref1.release().block();
	ref2.release().block();

	//second round
	ref1 = pool.acquire().block();
	ref2 = pool.acquire().block();
	Thread.sleep(300);
	ref1.release().block();
	ref2.release().block();

	//extra acquire to show 3 allocations
	pool.acquire().block().release().block();

	assertThat(allocCounter).as("allocations").hasValue(3);
	assertThat(destroyCounter).as("destructions").hasValue(2);

	assertThat(recorder.getLifetimeHistogram().getMinNonZeroValue())
			.isCloseTo(550L, Offset.offset(30L));
}
 
Example #22
Source File: NearCacheSessionStoreIT.java    From vertx-vaadin with MIT License 5 votes vote down vote up
@Test
public void createSession(TestContext context) {

    Vertx vertx = rule.vertx();
    SessionStore sessionStore = NearCacheSessionStore.create(vertx);
    long beforeCreationTime = System.currentTimeMillis();
    Session session = sessionStore.createSession(3600);
    assertThat(session.id()).isNotEmpty();
    assertThat(session.timeout()).isEqualTo(3600);
    assertThat(session.lastAccessed()).isCloseTo(beforeCreationTime, Offset.offset(100L));
    assertThat(session.isDestroyed()).isFalse();

}
 
Example #23
Source File: FluentEqualityConfig.java    From curiostack with MIT License 5 votes vote down vote up
final FluentEqualityConfig usingDoubleToleranceForFieldDescriptors(
    double tolerance, Iterable<FieldDescriptor> fieldDescriptors) {
  return toBuilder()
      .setDoubleCorrespondenceMap(
          doubleCorrespondenceMap()
              .with(
                  FieldScopeLogic.none().allowingFieldDescriptorsNonRecursive(fieldDescriptors),
                  Offset.strictOffset(tolerance)))
      .addUsingCorrespondenceFieldDescriptorsString(
          ".usingDoubleTolerance(" + tolerance + ", %s)", fieldDescriptors)
      .build();
}
 
Example #24
Source File: FluentEqualityConfig.java    From curiostack with MIT License 5 votes vote down vote up
final FluentEqualityConfig usingFloatToleranceForFields(
    float tolerance, Iterable<Integer> fieldNumbers) {
  return toBuilder()
      .setFloatCorrespondenceMap(
          floatCorrespondenceMap()
              .with(
                  FieldScopeLogic.none().allowingFieldsNonRecursive(fieldNumbers),
                  Offset.strictOffset(tolerance)))
      .addUsingCorrespondenceFieldNumbersString(
          ".usingFloatTolerance(" + tolerance + ", %s)", fieldNumbers)
      .build();
}
 
Example #25
Source File: FluentEqualityConfig.java    From curiostack with MIT License 5 votes vote down vote up
final FluentEqualityConfig usingFloatToleranceForFieldDescriptors(
    float tolerance, Iterable<FieldDescriptor> fieldDescriptors) {
  return toBuilder()
      .setFloatCorrespondenceMap(
          floatCorrespondenceMap()
              .with(
                  FieldScopeLogic.none().allowingFieldDescriptorsNonRecursive(fieldDescriptors),
                  Offset.strictOffset(tolerance)))
      .addUsingCorrespondenceFieldDescriptorsString(
          ".usingFloatTolerance(" + tolerance + ", %s)", fieldDescriptors)
      .build();
}
 
Example #26
Source File: ColorAssert.java    From gifencoder with Apache License 2.0 5 votes vote down vote up
ColorAssert isEqualTo(Color expected, Offset<Double> offset) {
  for (int i = 0; i < 3; ++i) {
    if (Math.abs(expected.getComponent(i) - actual.getComponent(i)) > offset.value) {
      failWithMessage("Expected <%s> but received <%s>.", expected, actual);
    }
  }
  return this;
}
 
Example #27
Source File: WeatherServiceTest.java    From spring-boot-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void getWeather() {
	this.server.expect(
			requestTo(URL + "weather?q=barcelona,es&APPID=test-ABC"))
			.andRespond(withSuccess(
					new ClassPathResource("weather-barcelona.json", getClass()),
					MediaType.APPLICATION_JSON));
	Weather forecast = this.weatherService.getWeather("es", "barcelona");
	assertThat(forecast.getName()).isEqualTo("Barcelona");
	assertThat(forecast.getTemperature()).isEqualTo(286.72, Offset.offset(0.1));
	assertThat(forecast.getWeatherId()).isEqualTo(800);
	assertThat(forecast.getWeatherIcon()).isEqualTo("01d");
	this.server.verify();
}
 
Example #28
Source File: BuyerSteps.java    From serenity-documentation with Apache License 2.0 5 votes vote down vote up
@Step
public void should_see_total_including_shipping_for(ListingItem selectedItem) {
    OrderCostSummary orderCostSummary
            = cartPage.getOrderCostSummaryFor(selectedItem).get();

    double itemTotal = orderCostSummary.getItemTotal();
    double shipping = orderCostSummary.getShipping();
    double totalCost = orderCostSummary.getTotalCost();

    assertThat(itemTotal).isEqualTo(selectedItem.getPrice());
    assertThat(shipping).isGreaterThan(0.0);
    assertThat(totalCost).isCloseTo(itemTotal + shipping, Offset.offset(0.001));
}
 
Example #29
Source File: RotateShapesTest.java    From latexdraw with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected Stream<Runnable> doCheckers() {
	return Stream.of(() -> {
		assertThat(shape.getRotationAngle()).isEqualTo(rotationAngle, Offset.offset(0.0001));
		assertThat(shape.isModified()).isTrue();
	});
}
 
Example #30
Source File: RotateShapesTest.java    From latexdraw with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected Stream<Runnable> undoCheckers() {
	return Stream.of(() -> {
		assertThat(shape.getRotationAngle()).isEqualTo(0d, Offset.offset(0.0001));
		assertThat(shape.isModified()).isFalse();
	});
}