Skip to content

Commit

Permalink
JUnit Migration - Migrated exception assertion to Junit5 AssertThrows (
Browse files Browse the repository at this point in the history
…dtinit#1133)

* Migrated exception assertion to assertThrows on BlackblazeDataTransferTest

* Update BackblazeDataTransferClientTest.java

Summary: 

Test Plan: 

Reviewers: 

Subscribers: 

Tasks: 

Tags: 


Differential Revision: https://phabricator.intern.facebook.com/D38427899

* Exception assert migration [1/2] junit 5

Summary: 

Test Plan: 

Reviewers: 

Subscribers: 

Tasks: 

Tags:

* exception assertion migration 2/2

Summary:

Test Plan:

Reviewers:

Subscribers:

Tasks:

Tags:

Differential Revision: https://phabricator.intern.facebook.com/D38456882

* [1/2] Migrate exception assert to Junit5

Summary: 

Test Plan: 

Reviewers: 

Subscribers: 

Tasks: 

Tags: 









Differential Revision: https://phabricator.intern.facebook.com/D38427899

* remove try catch block inside assertThrows method

* [2/2] Migrate exception assertion to Junit5



Differential Revision: https://phabricator.intern.facebook.com/D38456882

* removed unused imports

Co-authored-by: Ernest Sadykov <[email protected]>
  • Loading branch information
chaaransen and xokker committed Aug 11, 2022
1 parent 468d34c commit 4c8dc20
Show file tree
Hide file tree
Showing 6 changed files with 99 additions and 62 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,14 @@

package org.datatransferproject.transfer.facebook.photos;

import static com.google.common.truth.Truth.assertThat;
import static org.datatransferproject.transfer.facebook.photos.FacebookPhotosExporter.PHOTO_TOKEN_PREFIX;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import com.google.common.collect.Lists;
import com.restfb.Connection;
import com.restfb.types.Album;
Expand Down Expand Up @@ -44,14 +52,8 @@
import org.mockito.ArgumentMatchers;
import org.mockito.Mockito;

import static com.google.common.truth.Truth.assertThat;
import static org.datatransferproject.transfer.facebook.photos.FacebookPhotosExporter.PHOTO_TOKEN_PREFIX;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class FacebookPhotosExporterTest {

private static final String ALBUM_NAME = "My Album";
private static final String ALBUM_ID = "1946595";
private static final String ALBUM_DESCRIPTION = "This is a test album";
Expand Down Expand Up @@ -181,11 +183,13 @@ public void testSpecifiedAlbums() throws CopyExceptionWithFailureReason {
.contains(new IdOnlyContainerResource(ALBUM_ID));
}

@Test(expected = IllegalStateException.class)
@Test
public void testIllegalExport() throws CopyExceptionWithFailureReason {
facebookPhotosExporter.export(
uuid,
new TokensAndUrlAuthData("accessToken", null, null),
Optional.of(new ExportInformation(new StringPaginationToken(PHOTO_TOKEN_PREFIX), null)));
assertThrows(IllegalStateException.class, () -> {
facebookPhotosExporter.export(
uuid,
new TokensAndUrlAuthData("accessToken", null, null),
Optional.of(new ExportInformation(new StringPaginationToken(PHOTO_TOKEN_PREFIX), null)));
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
Expand Down Expand Up @@ -144,9 +145,9 @@ public void importTwoPhotos() throws Exception {
Mockito.when(googlePhotosInterface.uploadPhotoContent(any())).thenReturn("token1", "token2");
BatchMediaItemResponse batchMediaItemResponse =
new BatchMediaItemResponse(
new NewMediaItemResult[] {
buildMediaItemResult("token1", Code.OK_VALUE),
buildMediaItemResult("token2", Code.OK_VALUE)
new NewMediaItemResult[]{
buildMediaItemResult("token1", Code.OK_VALUE),
buildMediaItemResult("token2", Code.OK_VALUE)
});
Mockito.when(googlePhotosInterface.createPhotos(any(NewMediaItemUpload.class)))
.thenReturn(batchMediaItemResponse);
Expand Down Expand Up @@ -202,9 +203,9 @@ public void importTwoPhotosWithFailure() throws Exception {
Mockito.when(googlePhotosInterface.uploadPhotoContent(any())).thenReturn("token1", "token2");
BatchMediaItemResponse batchMediaItemResponse =
new BatchMediaItemResponse(
new NewMediaItemResult[] {
buildMediaItemResult("token1", Code.OK_VALUE),
buildMediaItemResult("token2", Code.UNAUTHENTICATED_VALUE)
new NewMediaItemResult[]{
buildMediaItemResult("token1", Code.OK_VALUE),
buildMediaItemResult("token2", Code.UNAUTHENTICATED_VALUE)
});
Mockito.when(googlePhotosInterface.createPhotos(any(NewMediaItemUpload.class)))
.thenReturn(batchMediaItemResponse);
Expand Down Expand Up @@ -308,7 +309,7 @@ public void importPhotoInTempStore() throws Exception {

BatchMediaItemResponse batchMediaItemResponse =
new BatchMediaItemResponse(
new NewMediaItemResult[] {buildMediaItemResult("token1", Code.OK_VALUE)});
new NewMediaItemResult[]{buildMediaItemResult("token1", Code.OK_VALUE)});

Mockito.when(googlePhotosInterface.createPhotos(any(NewMediaItemUpload.class)))
.thenReturn(batchMediaItemResponse);
Expand Down Expand Up @@ -354,7 +355,7 @@ public void importPhotoInTempStoreFailure() throws Exception {

BatchMediaItemResponse batchMediaItemResponse =
new BatchMediaItemResponse(
new NewMediaItemResult[] {buildMediaItemResult("token1", Code.OK_VALUE)});
new NewMediaItemResult[]{buildMediaItemResult("token1", Code.OK_VALUE)});

Mockito.when(googlePhotosInterface.createPhotos(any(NewMediaItemUpload.class)))
.thenReturn(batchMediaItemResponse);
Expand Down Expand Up @@ -410,7 +411,7 @@ public void importPhotoFailedToFindAlbum() throws Exception {
assertEquals(0, bytes);
}

@Test(expected = IOException.class)
@Test
public void importPhotoCreatePhotosOtherException() throws Exception {
PhotoModel photoModel =
new PhotoModel(
Expand Down Expand Up @@ -438,11 +439,13 @@ public void importPhotoCreatePhotosOtherException() throws Exception {
GoogleAlbum responseAlbum = new GoogleAlbum();
Mockito.when(googlePhotosInterface.getAlbum(any())).thenReturn(responseAlbum);

googlePhotosImporter.importPhotoBatch(
uuid,
Mockito.mock(TokensAndUrlAuthData.class),
Lists.newArrayList(photoModel),
executor,
NEW_ALBUM_ID);
assertThrows(IOException.class, () -> {
googlePhotosImporter.importPhotoBatch(
uuid,
Mockito.mock(TokensAndUrlAuthData.class),
Lists.newArrayList(photoModel),
executor,
NEW_ALBUM_ID);
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,14 @@
package org.datatransferproject.transfer.microsoft.media;

import static com.google.common.truth.Truth.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
import static org.mockito.Mockito.argThat;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
Expand All @@ -45,9 +51,8 @@
import org.datatransferproject.spi.transfer.types.PermissionDeniedException;
import org.datatransferproject.test.types.FakeIdempotentImportExecutor;
import org.datatransferproject.transfer.microsoft.common.MicrosoftCredentialFactory;
import org.datatransferproject.transfer.microsoft.driveModels.*;
import org.datatransferproject.types.common.models.media.MediaContainerResource;
import org.datatransferproject.types.common.models.media.MediaAlbum;
import org.datatransferproject.types.common.models.media.MediaContainerResource;
import org.datatransferproject.types.common.models.photos.PhotoModel;
import org.datatransferproject.types.transfer.auth.TokensAndUrlAuthData;
import org.junit.Before;
Expand All @@ -58,6 +63,7 @@
* More tests are needed to test request bodies and parameters.
*/
public class MicrosoftMediaImporterTest {

private static final int CHUNK_SIZE = 32000 * 1024; // 32000KiB
private final static String BASE_URL = "https://www.baseurl.com";
private final static UUID uuid = UUID.randomUUID();
Expand Down Expand Up @@ -97,7 +103,8 @@ public void testCleanAlbumNames() throws Exception {
List<MediaAlbum> albums =
ImmutableList.of(new MediaAlbum("id1", "album1.", "This is a fake albumb"));

MediaContainerResource data = new MediaContainerResource(albums, null /*phots*/, null /*videos*/);
MediaContainerResource data = new MediaContainerResource(albums, null /*phots*/,
null /*videos*/);

Call call = mock(Call.class);
doReturn(call).when(client).newCall(argThat((Request r) -> {
Expand All @@ -112,7 +119,7 @@ public void testCleanAlbumNames() throws Exception {
}

return r.url().toString().equals(
"https://www.baseurl.com/v1.0/me/drive/special/photo-video/children")
"https://www.baseurl.com/v1.0/me/drive/special/photo-video/children")
&& body.contains("album1_");
}));
Response response = mock(Response.class);
Expand All @@ -132,18 +139,19 @@ public void testCleanAlbumNames() throws Exception {
assertThat(result).isEqualTo(ImportResult.OK);
}

@Test(expected = PermissionDeniedException.class)
@Test
public void testImportItemPermissionDenied() throws Exception {
List<MediaAlbum> albums =
ImmutableList.of(new MediaAlbum("id1", "album1.", "This is a fake albumb"));

MediaContainerResource data = new MediaContainerResource(albums, null /*photos*/, null /*videos*/);
MediaContainerResource data = new MediaContainerResource(albums, null /*photos*/,
null /*videos*/);

Call call = mock(Call.class);
doReturn(call).when(client).newCall(
argThat((Request r)
-> r.url().toString().equals(
"https://www.baseurl.com/v1.0/me/drive/special/photo-video/children")));
-> r.url().toString().equals(
"https://www.baseurl.com/v1.0/me/drive/special/photo-video/children")));
Response response = mock(Response.class);
ResponseBody body = mock(ResponseBody.class);
when(body.bytes())
Expand All @@ -157,7 +165,9 @@ public void testImportItemPermissionDenied() throws Exception {
when(response.body()).thenReturn(body);
when(call.execute()).thenReturn(response);

ImportResult result = importer.importItem(uuid, executor, authData, data);
assertThrows(PermissionDeniedException.class, () -> {
ImportResult result = importer.importItem(uuid, executor, authData, data);
});
}

@Test
Expand All @@ -178,8 +188,8 @@ public void testImportItemAllSuccess() throws Exception {
Call call = mock(Call.class);
doReturn(call).when(client).newCall(
argThat((Request r)
-> r.url().toString().equals(
"https://www.baseurl.com/v1.0/me/drive/special/photo-video/children")));
-> r.url().toString().equals(
"https://www.baseurl.com/v1.0/me/drive/special/photo-video/children")));
Response response = mock(Response.class);
ResponseBody body = mock(ResponseBody.class);
when(body.bytes())
Expand All @@ -199,14 +209,14 @@ public void testImportItemAllSuccess() throws Exception {
ResponseBody body2 = mock(ResponseBody.class);
when(body2.bytes())
.thenReturn(ResponseBody
.create(MediaType.parse("application/json"),
"{\"uploadUrl\": \"https://scalia.com/link\"}")
.bytes());
.create(MediaType.parse("application/json"),
"{\"uploadUrl\": \"https://scalia.com/link\"}")
.bytes());
when(body2.string())
.thenReturn(ResponseBody
.create(MediaType.parse("application/json"),
"{\"uploadUrl\": \"https://scalia.com/link\"}")
.string());
.create(MediaType.parse("application/json"),
"{\"uploadUrl\": \"https://scalia.com/link\"}")
.string());
when(response2.code()).thenReturn(200);
when(response2.body()).thenReturn(body2);
when(call2.execute()).thenReturn(response2);
Expand All @@ -218,10 +228,10 @@ public void testImportItemAllSuccess() throws Exception {
ResponseBody body3 = mock(ResponseBody.class);
when(body3.bytes())
.thenReturn(ResponseBody.create(MediaType.parse("application/json"), "{\"id\": \"rand1\"}")
.bytes());
.bytes());
when(body3.string())
.thenReturn(ResponseBody.create(MediaType.parse("application/json"), "{\"id\": \"rand1\"}")
.string());
.string());
when(response3.code()).thenReturn(200);
when(response3.body()).thenReturn(body3);
when(call3.execute()).thenReturn(response3);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,14 @@
package org.datatransferproject.transfer.microsoft.photos;

import static com.google.common.truth.Truth.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
import static org.mockito.Mockito.argThat;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
Expand All @@ -45,7 +51,6 @@
import org.datatransferproject.spi.transfer.types.PermissionDeniedException;
import org.datatransferproject.test.types.FakeIdempotentImportExecutor;
import org.datatransferproject.transfer.microsoft.common.MicrosoftCredentialFactory;
import org.datatransferproject.transfer.microsoft.driveModels.*;
import org.datatransferproject.types.common.models.photos.PhotoAlbum;
import org.datatransferproject.types.common.models.photos.PhotoModel;
import org.datatransferproject.types.common.models.photos.PhotosContainerResource;
Expand Down Expand Up @@ -140,7 +145,7 @@ public void testCleanAlbumNames() throws Exception {
assertThat(result).isEqualTo(ImportResult.OK);
}

@Test(expected = PermissionDeniedException.class)
@Test
public void testImportItemPermissionDenied() throws Exception {
List<PhotoAlbum> albums =
ImmutableList.of(new PhotoAlbum("id1", "album1.", "This is a fake albumb"));
Expand All @@ -162,7 +167,9 @@ public void testImportItemPermissionDenied() throws Exception {
when(response.body()).thenReturn(body);
when(call.execute()).thenReturn(response);

ImportResult result = importer.importItem(uuid, executor, authData, data);
assertThrows(PermissionDeniedException.class, () -> {
ImportResult result = importer.importItem(uuid, executor, authData, data);
});
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import static org.datatransferproject.spi.transfer.idempotentexecutor.ItemImportResult.Status.SUCCESS;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;

import org.junit.Test;

Expand All @@ -15,23 +16,31 @@ public void testNullBytesIsOk() {
assertFalse(result.hasBytes());
}

@Test(expected = IllegalStateException.class)
@Test
public void testNullBytesThrowOnGet() {
ItemImportResult.success("blabla", null).getBytes();
assertThrows(IllegalStateException.class, () -> {
ItemImportResult.success("blabla", null).getBytes();
});
}

@Test(expected = NullPointerException.class)
@Test
public void testSuccessWithNoData() {
ItemImportResult.success(null, 0L);
assertThrows(NullPointerException.class, () -> {
ItemImportResult.success(null, 0L);
});
}

@Test(expected = IllegalArgumentException.class)
@Test
public void testFailWithIncorrectBytes() {
ItemImportResult.success("blabla", -1L);
assertThrows(IllegalArgumentException.class, () -> {
ItemImportResult.success("blabla", -1L);
});
}

@Test(expected = NullPointerException.class)
@Test
public void testErrorWithNoException() {
ItemImportResult.error(null, 10L);
assertThrows(NullPointerException.class, () -> {
ItemImportResult.error(null, 10L);
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import static org.apache.commons.lang3.RandomUtils.nextInt;
import static org.apache.commons.lang3.RandomUtils.nextLong;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
Expand All @@ -26,6 +27,7 @@
import org.junit.Before;
import org.junit.Test;


public class CallableSizeCalculatorTest {

private UUID jobId;
Expand Down Expand Up @@ -80,12 +82,14 @@ public void testSizeIsNotProvided() throws Exception {
Truth.assertThat(nextByte).isEqualTo(-1);
}

@Test(expected = IOException.class)
@Test
public void testExceptionIsThrown() throws Exception {
when(connectionProvider.getInputStreamForItem(any(), any()))
.thenThrow(new IOException("oh no!"));
new CallableSizeCalculator(jobId, connectionProvider,
Collections.singleton(createItem("1-3242"))).call();
assertThrows(IOException.class, () -> {
new CallableSizeCalculator(jobId, connectionProvider,
Collections.singleton(createItem("1-3242"))).call();
});
}

private DownloadableItem createItem(String dataId) {
Expand Down

0 comments on commit 4c8dc20

Please sign in to comment.