S3Manager { @NonNull public Observable<String> upload(@NonNull final File file, @NonNull final String subDirectoryPath) { return s3ClientFactory.getAmazonS3() .flatMap(amazonS3 -> { if (amazonS3.isPresent()) { return s3KeyGeneratorFactory.get() .flatMap(s3KeyGenerator -> Observable.fromCallable(() -> { final String key = subDirectoryPath + s3KeyGenerator.getS3Key() + file.getName(); amazonS3.get().putObject(BUCKET, key, file); try { return amazonS3.get().getResourceUrl(BUCKET, key); } catch (Exception e) { throw new IOException("Caught Amazon S3 exception", e); } })); } else { return Observable.error(new Exception("Failed to initialize the S3 client")); } }); } @Inject  S3Manager(CognitoManager cognitoManager); @VisibleForTesting  S3Manager(@NonNull S3ClientFactory s3ClientFactory, @NonNull S3KeyGeneratorFactory s3KeyGeneratorFactory); @NonNull Observable<String> upload(@NonNull final File file, @NonNull final String subDirectoryPath);  }
@Test public void uploadWithoutS3InstanceFails() { when(s3ClientFactory.getAmazonS3()).thenReturn(Observable.just(Optional.<AmazonS3Client>absent())); TestObserver<String> testObserver = s3Manager.upload(file, PATH).test(); verify(amazonS3Client, never()).putObject("smartreceipts", FULL_KEY_PATH, file); testObserver.assertNoValues(); testObserver.assertNotComplete(); testObserver.assertError(Exception.class); }
@Test public void uploadFails() { final AmazonClientException exception = new AmazonClientException("test"); when(amazonS3Client.putObject("smartreceipts", FULL_KEY_PATH, file)).thenThrow(exception); TestObserver<String> testObserver = s3Manager.upload(file, PATH).test(); verify(amazonS3Client).putObject("smartreceipts", FULL_KEY_PATH, file); testObserver.assertNoValues(); testObserver.assertNotComplete(); testObserver.assertError(exception); }
@Test public void uploadSuccess() { TestObserver<String> testObserver = s3Manager.upload(file, PATH).test(); verify(amazonS3Client).putObject("smartreceipts", FULL_KEY_PATH, file); testObserver.assertValue(URL); testObserver.assertComplete(); testObserver.assertNoErrors(); }