Skip to content

Commit

Permalink
junit-team#946 - Updated TemporaryFolder.newFolder() to give a better…
Browse files Browse the repository at this point in the history
… error message if a path contains a slash
  • Loading branch information
priav03 committed Aug 12, 2014
1 parent 7c6c36d commit 3b544f5
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
16 changes: 16 additions & 0 deletions src/main/java/org/junit/rules/TemporaryFolder.java
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ public File newFolder(String... folderNames) throws IOException {
File file = getRoot();
for (int i = 0; i < folderNames.length; i++) {
String folderName = folderNames[i];
validateFolderName(folderName);
file = new File(file, folderName);
if (!file.mkdir() && isLastElementInArray(i, folderNames)) {
throw new IOException(
Expand All @@ -100,6 +101,21 @@ public File newFolder(String... folderNames) throws IOException {
}
return file;
}

/**
* Validates if multiple path components were used while creating a folder.
*
* @param folderName
* Name of the folder being created
*/
private void validateFolderName(String folderName) throws IOException {
File tempFile = new File(folderName);
if (tempFile.getParent() != null) {
String errorMsg = "Folder name cannot consist of multiple path components separated by a file separator."
+ " Please use newFolder('MyParentFolder','MyFolder') to create hierarchies of folders";
throw new IOException(errorMsg);
}
}

private boolean isLastElementInArray(int index, String[] array) {
return index == array.length - 1;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,16 @@ public void newFolderWithGivenFolderThrowsIllegalArgumentExceptionIfFolderExists
thrown.expectMessage("a folder with the name 'level1' already exists");
tempFolder.newFolder("level1");
}


@Test
public void newFolderWithGivenFolderThrowsIOExceptionIfFolderNameConsistsOfMultiplePathComponents()
throws IOException {
tempFolder.create();
thrown.expect(IOException.class);
thrown.expectMessage("name cannot consist of multiple path components");
tempFolder.newFolder("temp1/temp2");
}

@Test
public void newFolderWithGivenPathThrowsIllegalArgumentExceptionIfPathExists() throws IOException {
tempFolder.create();
Expand All @@ -95,6 +104,15 @@ public void newFolderWithGivenPathThrowsIllegalArgumentExceptionIfPathExists() t
tempFolder.newFolder("level1", "level2", "level3");
}

@Test
public void newFolderWithGivenPathThrowsIOExceptionIfFolderNamesConsistOfMultiplePathComponents()
throws IOException {
tempFolder.create();
thrown.expect(IOException.class);
thrown.expectMessage("name cannot consist of multiple path components");
tempFolder.newFolder("temp1", "temp2", "temp3/temp4");
}

@Test
public void createInitializesRootFolder() throws IOException {
tempFolder.create();
Expand Down

0 comments on commit 3b544f5

Please sign in to comment.