Generate fixed length passwords

Avoids bugs where tests succeed with an average sized password but fail when the password length is at the allowed extremes.
This commit is contained in:
Svetoslav Neykov 2017-08-01 16:12:59 +03:00
parent 5bcf7c4757
commit 640e04b315
2 changed files with 18 additions and 4 deletions

View File

@ -19,16 +19,18 @@ package org.jclouds.util;
import java.util.Random; import java.util.Random;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
public class Passwords { public class Passwords {
private static final Random random = new Random(); private static final Random random = new Random();
private static final int MIN_CHAR = 8; private static final int GENERATE_PASSWORD_LENGTH = 30;
private static final int MAX_CHAR = 50; private static final int VALID_PASSWORD_MIN_LENGTH = 8;
private static final int VALID_PASSWORD_MAX_LENGTH = 50;
private static final String PASSWORD_FORMAT = String.format( private static final String PASSWORD_FORMAT = String.format(
"[a-zA-Z0-9][^iIloOwWyYzZ10]{%d,%d}", MIN_CHAR - 1, MAX_CHAR); "[a-zA-Z0-9][^iIloOwWyYzZ10]{%d,%d}", VALID_PASSWORD_MIN_LENGTH - 1, VALID_PASSWORD_MAX_LENGTH);
private static final Pattern PASSWORD_PATTERN = Pattern.compile(PASSWORD_FORMAT); private static final Pattern PASSWORD_PATTERN = Pattern.compile(PASSWORD_FORMAT);
private static final ImmutableSet<Character> INVALID_CHARS = ImmutableSet.<Character>of( private static final ImmutableSet<Character> INVALID_CHARS = ImmutableSet.<Character>of(
@ -39,7 +41,11 @@ public class Passwords {
} }
public static String generate() { public static String generate() {
int count = random.nextInt(MAX_CHAR - MIN_CHAR) + MIN_CHAR; return generate(GENERATE_PASSWORD_LENGTH);
}
public static String generate(int count) {
Preconditions.checkArgument(count > 0, "Password length must be a positive number");
final char[] buffer = new char[count]; final char[] buffer = new char[count];

View File

@ -20,8 +20,10 @@ import com.google.common.collect.ImmutableList;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import java.util.List; import java.util.List;
import java.util.Random;
import static org.jclouds.util.Passwords.isValidPassword; import static org.jclouds.util.Passwords.isValidPassword;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue; import static org.testng.Assert.assertTrue;
@ -52,4 +54,10 @@ public class PasswordsTest {
assertTrue(isValidPassword(pwd), "Failed with: " + pwd); assertTrue(isValidPassword(pwd), "Failed with: " + pwd);
} }
} }
@Test
public void testGeneratorGeneratesRequestedLength() {
int passwordLength = new Random().nextInt(40) + 10;
assertEquals(Passwords.generate(passwordLength).length(), passwordLength);
}
} }