com.google.api.client.testing.http.FixedClock Java Examples

The following examples show how to use com.google.api.client.testing.http.FixedClock. 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: FirebaseTokenFactoryTest.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void checkSignatureForToken() throws Exception {
  KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
  keyGen.initialize(512);
  KeyPair keys = keyGen.genKeyPair();

  FixedClock clock = new FixedClock(2002L);

  FirebaseTokenFactory tokenFactory = new FirebaseTokenFactory(FACTORY, clock,
      new TestCryptoSigner(keys.getPrivate()));

  String jwt = tokenFactory.createSignedCustomAuthTokenForUser(USER_ID, EXTRA_CLAIMS);
  FirebaseCustomAuthToken signedJwt = FirebaseCustomAuthToken.parse(FACTORY, jwt);
  assertEquals("RS256", signedJwt.getHeader().getAlgorithm());
  assertEquals(ISSUER, signedJwt.getPayload().getIssuer());
  assertEquals(ISSUER, signedJwt.getPayload().getSubject());
  assertEquals(USER_ID, signedJwt.getPayload().getUid());
  assertEquals(2L, signedJwt.getPayload().getIssuedAtTimeSeconds().longValue());
  assertTrue(TestUtils.verifySignature(signedJwt, ImmutableList.of(keys.getPublic())));

  jwt = tokenFactory.createSignedCustomAuthTokenForUser(USER_ID);
  signedJwt = FirebaseCustomAuthToken.parse(FACTORY, jwt);
  assertEquals("RS256", signedJwt.getHeader().getAlgorithm());
  assertEquals(ISSUER, signedJwt.getPayload().getIssuer());
  assertEquals(ISSUER, signedJwt.getPayload().getSubject());
  assertEquals(USER_ID, signedJwt.getPayload().getUid());
  assertEquals(2L, signedJwt.getPayload().getIssuedAtTimeSeconds().longValue());
  assertTrue(TestUtils.verifySignature(signedJwt, ImmutableList.of(keys.getPublic())));
}
 
Example #2
Source File: FirebaseTokenFactoryTest.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void failsWhenUidIsNull() throws Exception {
  KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
  keyGen.initialize(512);
  KeyPair keys = keyGen.genKeyPair();

  FixedClock clock = new FixedClock(2002L);

  FirebaseTokenFactory tokenFactory = new FirebaseTokenFactory(FACTORY, clock,
      new TestCryptoSigner(keys.getPrivate()));

  thrown.expect(IllegalArgumentException.class);
  tokenFactory.createSignedCustomAuthTokenForUser(null);
}
 
Example #3
Source File: FirebaseTokenFactoryTest.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void failsWhenUidIsTooLong() throws Exception {
  KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
  keyGen.initialize(512);
  KeyPair keys = keyGen.genKeyPair();

  FixedClock clock = new FixedClock(2002L);

  FirebaseTokenFactory tokenFactory = new FirebaseTokenFactory(FACTORY, clock,
      new TestCryptoSigner(keys.getPrivate()));

  thrown.expect(IllegalArgumentException.class);
  tokenFactory.createSignedCustomAuthTokenForUser(
      Strings.repeat("a", 129));
}
 
Example #4
Source File: FirebaseTokenFactoryTest.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void failsWhenExtraClaimsContainsReservedKey() throws Exception {
  KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
  keyGen.initialize(512);
  KeyPair keys = keyGen.genKeyPair();

  FixedClock clock = new FixedClock(2002L);

  FirebaseTokenFactory tokenFactory = new FirebaseTokenFactory(FACTORY, clock,
      new TestCryptoSigner(keys.getPrivate()));

  Map<String, Object> extraClaims = ImmutableMap.<String, Object>of("iss", "repeat issuer");
  thrown.expect(IllegalArgumentException.class);
  tokenFactory.createSignedCustomAuthTokenForUser(USER_ID, extraClaims);
}
 
Example #5
Source File: RetryUnsuccessfulResponseHandlerTest.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testRetryAfterGivenAsDate() throws IOException {
  SimpleDateFormat dateFormat =
          new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US);
  dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
  Date date = new Date(1000);
  Clock clock = new FixedClock(date.getTime());
  String retryAfter = dateFormat.format(new Date(date.getTime() + 30000));

  MultipleCallSleeper sleeper = new MultipleCallSleeper();
  RetryUnsuccessfulResponseHandler handler = new RetryUnsuccessfulResponseHandler(
      testRetryConfig(sleeper), clock);
  CountingLowLevelHttpRequest failingRequest = CountingLowLevelHttpRequest.fromStatus(
      503, ImmutableMap.of("retry-after", retryAfter));
  HttpRequest request = TestUtils.createRequest(failingRequest);
  request.setUnsuccessfulResponseHandler(handler);
  request.setNumberOfRetries(4);

  try {
    request.execute();
    fail("No exception thrown for HTTP error");
  } catch (HttpResponseException e) {
    assertEquals(503, e.getStatusCode());
  }

  assertEquals(4, sleeper.getCount());
  assertArrayEquals(new long[]{30000, 30000, 30000, 30000}, sleeper.getDelays());
  assertEquals(5, failingRequest.getCount());
}
 
Example #6
Source File: DataflowWorkProgressUpdaterTest.java    From beam with Apache License 2.0 5 votes vote down vote up
@Before
public void initMocksAndWorkflowServiceAndWorkerAndWork() {
  MockitoAnnotations.initMocks(this);
  startTime = 0L;
  clock = new FixedClock(startTime);
  executor = new StubbedExecutor(clock);

  WorkItem workItem = new WorkItem();
  workItem.setProjectId(PROJECT_ID);
  workItem.setJobId(JOB_ID);
  workItem.setId(WORK_ID);
  workItem.setLeaseExpireTime(toCloudTime(new Instant(clock.currentTimeMillis() + 1000)));
  workItem.setReportStatusInterval(toCloudDuration(Duration.millis(300)));
  workItem.setInitialReportIndex(1L);

  progressUpdater =
      new DataflowWorkProgressUpdater(
          workItemStatusClient, workItem, worker, executor.getExecutor(), clock, hotKeyLogger) {

        // Shorten reporting interval boundaries for faster testing.
        @Override
        protected long getMinReportingInterval() {
          return 100;
        }

        @Override
        protected long getLeaseRenewalLatencyMargin() {
          return 150;
        }
      };
}
 
Example #7
Source File: StubbedExecutor.java    From beam with Apache License 2.0 5 votes vote down vote up
public StubbedExecutor(FixedClock c) {
  this.clock = c;
  MockitoAnnotations.initMocks(this);
  when(executor.schedule(any(Runnable.class), anyLong(), any(TimeUnit.class)))
      .thenAnswer(
          invocation -> {
            assertNull(lastRunnable);
            Object[] args = invocation.getArguments();
            lastRunnable = (Runnable) args[0];
            lastDelay = (long) args[1];
            LOG.debug("{}: Saving task for later.", clock.currentTimeMillis());
            return null;
          });
}
 
Example #8
Source File: WorkProgressUpdaterTest.java    From beam with Apache License 2.0 5 votes vote down vote up
@Before
@SuppressWarnings("GuardedBy")
public void init() {
  MockitoAnnotations.initMocks(this);
  startTimeMs = 2134785689L; // Some random start time.
  checkpointPeriodSec = 20;
  checkpointTimeMs = startTimeMs + ((long) checkpointPeriodSec) * 1000;
  clock = new FixedClock(startTimeMs);
  executor = new StubbedExecutor(clock);
  progressUpdater =
      new WorkProgressUpdater(workExecutor, checkpointPeriodSec, executor.getExecutor(), clock) {
        @Override
        protected void reportProgressHelper() throws Exception {
          Exception e = progressHelper.shouldThrow();
          if (e != null) {
            throw e;
          }

          progressReportIntervalMs = progressHelper.reportProgress(dynamicSplitResultToReport);
          dynamicSplitResultToReport = null;
          if (progressHelper.shouldCheckpoint()) {
            checkpointState = CheckpointState.CHECKPOINT_REQUESTED;
            if (tryCheckpointIfNeeded()) {
              progressReportIntervalMs = 0;
            }
          }
        }

        @Override
        protected long getWorkUnitLeaseExpirationTimestamp() {
          return initialLeaseExpirationMs;
        }

        @Override
        protected String workString() {
          return "wi123";
        }
      };
}
 
Example #9
Source File: GoogleIdTokenVerifierTest.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
public void testBuilder() throws Exception {
  GoogleIdTokenVerifier.Builder builder = new GoogleIdTokenVerifier.Builder(
      new GooglePublicKeysManagerTest.PublicCertsMockHttpTransport(), new JacksonFactory()).setIssuer(
      ISSUER).setAudience(TRUSTED_CLIENT_IDS);
  assertEquals(Clock.SYSTEM, builder.getClock());
  assertEquals(ISSUER, builder.getIssuer());
  assertTrue(TRUSTED_CLIENT_IDS.equals(builder.getAudience()));
  Clock clock = new FixedClock(4);
  builder.setClock(clock);
  assertEquals(clock, builder.getClock());
  IdTokenVerifier verifier = builder.build();
  assertEquals(clock, verifier.getClock());
  assertEquals(ISSUER, verifier.getIssuer());
  assertEquals(TRUSTED_CLIENT_IDS, Lists.newArrayList(verifier.getAudience()));
}
 
Example #10
Source File: GooglePublicKeysManagerTest.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
public void testLoadCerts_cache() throws Exception {
  PublicCertsMockHttpTransport transport = new PublicCertsMockHttpTransport();
  transport.useAgeHeader = true;
  GooglePublicKeysManager certs = new GooglePublicKeysManager.Builder(
      transport, new JacksonFactory()).setClock(new FixedClock(100)).build();

  certs.refresh();
  assertEquals(2, certs.getPublicKeys().size());
  assertEquals(100 + (MAX_AGE - AGE) * 1000, certs.getExpirationTimeMilliseconds());
}
 
Example #11
Source File: HotKeyLoggerTest.java    From beam with Apache License 2.0 4 votes vote down vote up
@Before
public void SetUp() {
  clock = new FixedClock(Clock.SYSTEM.currentTimeMillis());
}