@Test
public void shouldNotConcurrentlyCreateServiceAccountKeysAndSecrets()
    throws IOException, ExecutionException, InterruptedException {

  final ServiceAccountKey jsonKey = new ServiceAccountKey();
  jsonKey.setName("key.json");
  jsonKey.setPrivateKeyData("json-private-key-data");
  final ServiceAccountKey p12Key = new ServiceAccountKey();
  p12Key.setName("key.p12");
  p12Key.setPrivateKeyData("p12-private-key-data");
  CompletableFuture<Boolean> accountExistsFuture = new CompletableFuture<>();
  // Make the service account existence check block
  when(serviceAccountKeyManager.serviceAccountExists(SERVICE_ACCOUNT)).thenAnswer(a -> accountExistsFuture.get());
  when(serviceAccountKeyManager.createJsonKey(any(String.class))).thenReturn(jsonKey);
  when(serviceAccountKeyManager.createP12Key(any(String.class))).thenReturn(p12Key);
  // Run two concurrent requests for the same service account secret
  final Future<String> f1 = executor.submit(
      () -> sut.ensureServiceAccountKeySecret(WORKFLOW_ID.toString(), SERVICE_ACCOUNT));
  final Future<String> f2 = executor.submit(
      () -> sut.ensureServiceAccountKeySecret(WORKFLOW_ID.toString(), SERVICE_ACCOUNT));
  // Wait for a call to the blocking service account existence method
  verify(serviceAccountKeyManager, timeout(30_000)).serviceAccountExists(SERVICE_ACCOUNT);
  Thread.sleep(5000);
  // Verify that we only got one call
  verify(serviceAccountKeyManager, times(1)).serviceAccountExists(SERVICE_ACCOUNT);
  // Unblock the calling thread
  accountExistsFuture.complete(true);
  // Wait for both requests to finish
  final String secret1 = f1.get();
  final String secret2 = f2.get();
  // Check that only one secret was created
  verify(k8sClient, times(1)).createSecret(secretCaptor.capture());
  final Secret createdSecret = secretCaptor.getValue();
  // Check that both requests returned the same secret name
  assertThat(secret1, is(createdSecret.getMetadata().getName()));
  assertThat(secret2, is(createdSecret.getMetadata().getName()));
  // Check that only one json and one p12 keys were created
  verify(serviceAccountKeyManager, times(1)).createJsonKey(SERVICE_ACCOUNT);
  verify(serviceAccountKeyManager, times(1)).createP12Key(SERVICE_ACCOUNT);
}