OcrSaveResult implements BackgroundFunction<PubSubMessage> { @Override public void accept(PubSubMessage pubSubMessage, Context context) { OcrTranslateApiMessage ocrMessage = OcrTranslateApiMessage.fromPubsubData( pubSubMessage.getData().getBytes(StandardCharsets.UTF_8)); logger.info("Received request to save file " + ocrMessage.getFilename()); String newFileName = String.format( "%s_to_%s.txt", ocrMessage.getFilename(), ocrMessage.getLang()); logger.info(String.format("Saving result to %s in bucket %s", newFileName, RESULT_BUCKET)); BlobInfo blobInfo = BlobInfo.newBuilder(BlobId.of(RESULT_BUCKET, newFileName)).build(); STORAGE.create(blobInfo, ocrMessage.getText().getBytes(StandardCharsets.UTF_8)); logger.info("File saved"); }  @Override void accept(PubSubMessage pubSubMessage, Context context);  }
@Test(expected = IllegalArgumentException.class) public void functionsOcrSave_shouldValidateParams() throws IOException { PubSubMessage message = new PubSubMessage(); message.setData(new String(Base64.getEncoder().encode("{}".getBytes()))); new OcrSaveResult().accept(message, null); }
@Test public void functionsOcrSave_shouldPublishTranslatedText() throws IOException { String text = "Wake up human!"; String filename = String.format("test-%s.jpg", RANDOM_STRING); String lang = "es"; JsonObject dataJson = new JsonObject(); dataJson.addProperty("text", text); dataJson.addProperty("filename", filename); dataJson.addProperty("lang", lang); PubSubMessage message = new PubSubMessage(); message.setData(new String(Base64.getEncoder().encode(gson.toJson(dataJson).getBytes()))); new OcrSaveResult().accept(message, null); String resultFilename = filename + "_to_es.txt"; List<LogRecord> logs = LOG_HANDLER.getStoredLogRecords(); String expectedMessage = String.format( "Saving result to %s in bucket %s", resultFilename, RESULT_BUCKET); Truth.assertThat(LOG_HANDLER.getStoredLogRecords().get(1).getMessage()).isEqualTo( expectedMessage); BlobInfo resultBlob = STORAGE.get(RESULT_BUCKET, resultFilename); assertThat(resultBlob).isNotNull(); }