Upgrade jcommander (#2398)

This commit is contained in:
Lai Jiang
2024-04-10 17:34:11 +00:00
committed by GitHub
parent 2df583df1a
commit 496a781572
38 changed files with 1034 additions and 1092 deletions
@@ -23,7 +23,6 @@ import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.ParameterDescription;
import com.beust.jcommander.Parameters;
import com.google.auto.value.AutoValue;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Ascii;
import com.google.common.collect.ImmutableList;
@@ -47,7 +46,6 @@ import java.util.Arrays;
import java.util.List;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import jline.Completor;
import jline.ConsoleReader;
@@ -87,7 +85,7 @@ public class ShellCommand implements Command {
* The runner we received in the constructor.
*
* <p>We might want to update this runner based on flags (e.g. --encapsulate_output), but these
* flags aren't available in the constructor so we have to do it in the {@link #run} function.
* flags aren't available in the constructor, so we have to do it in the {@link #run} function.
*/
private final CommandRunner originalRunner;
@@ -112,7 +110,7 @@ public class ShellCommand implements Command {
+ "command, allowing the output to be easily parsed by wrapper scripts.")
boolean encapsulateOutput = false;
public ShellCommand(CommandRunner runner) throws IOException {
ShellCommand(CommandRunner runner) throws IOException {
this.originalRunner = runner;
InputStream in = System.in;
if (System.console() != null) {
@@ -155,19 +153,13 @@ public class ShellCommand implements Command {
if (consoleReader != null) {
@SuppressWarnings("unchecked")
ImmutableList<Completor> completors = ImmutableList.copyOf(consoleReader.getCompletors());
completors
.forEach(consoleReader::removeCompletor);
completors.forEach(consoleReader::removeCompletor);
consoleReader.addCompletor(new JCommanderCompletor(jcommander));
}
return this;
}
private static class OutputEncapsulator implements CommandRunner {
private final CommandRunner runner;
private OutputEncapsulator(CommandRunner runner) {
this.runner = runner;
}
private record OutputEncapsulator(CommandRunner runner) implements CommandRunner {
/**
* Emit a success command separator.
@@ -233,7 +225,7 @@ public class ShellCommand implements Command {
// haven't been processed in the constructor.
CommandRunner runner =
encapsulateOutput ? new OutputEncapsulator(originalRunner) : originalRunner;
// On Production we want to be extra careful - to prevent accidental use.
// On Production, we want to be extra careful - to prevent accidental use.
boolean beExtraCareful = (RegistryToolEnvironment.get() == RegistryToolEnvironment.PRODUCTION);
setPrompt(RegistryToolEnvironment.get(), beExtraCareful);
String line;
@@ -245,7 +237,7 @@ public class ShellCommand implements Command {
&& lastTime.plus(IDLE_THRESHOLD).isBefore(clock.nowUtc())) {
throw new RuntimeException(
"Been idle for too long, while in 'extra careful' mode. "
+ "The last command was saved in history. Please rerun the shell and try again.");
+ "The last command was saved in history. Please rerun the shell and try again.");
}
lastTime = clock.nowUtc();
String[] lineArgs = parseCommand(line);
@@ -299,7 +291,7 @@ public class ShellCommand implements Command {
static class JCommanderCompletor implements Completor {
private static final ParamDoc DEFAULT_PARAM_DOC =
ParamDoc.create("[No documentation available]", ImmutableList.of());
new ParamDoc("[No documentation available]", ImmutableList.of());
/**
* Documentation for all the known command + argument combinations.
@@ -332,15 +324,11 @@ public class ShellCommand implements Command {
*
* <p>For now - "all possible options" are only known for enum parameters.
*/
@AutoValue
abstract static class ParamDoc {
abstract String documentation();
abstract ImmutableList<String> options();
record ParamDoc(String documentation, ImmutableList<String> options) {
static ParamDoc create(@Nullable ParameterDescription parameter) {
if (parameter == null) {
return create("[None]", ImmutableList.of());
return new ParamDoc("[None]", ImmutableList.of());
}
String type = parameter.getParameterized().getGenericType().toString();
Class<?> clazz = parameter.getParameterized().getType();
@@ -350,28 +338,19 @@ public class ShellCommand implements Command {
Arrays.stream(clazz.getEnumConstants())
.map(Object::toString)
.collect(toImmutableList());
type = options.stream().collect(Collectors.joining(", "));
type = String.join(", ", options);
}
if (type.startsWith("class ")) {
type = type.substring(6);
}
return create(
String.format(
"%s\n (%s)",
parameter.getDescription(),
type),
options);
}
static ParamDoc create(String documentation, ImmutableList<String> options) {
return new AutoValue_ShellCommand_JCommanderCompletor_ParamDoc(documentation, options);
return new ParamDoc(String.format("%s\n (%s)", parameter.getDescription(), type), options);
}
}
/**
* Populates the completions and documentation based on the JCommander.
*
* The input data is copied, so changing the jcommander after creation of the
* <p>The input data is copied, so changing the jcommander after creation of the
* JCommanderCompletor doesn't change the completions.
*/
JCommanderCompletor(JCommander jcommander) {
@@ -383,7 +362,13 @@ public class ShellCommand implements Command {
JCommander subCommander = entry.getValue();
// Add the "main" parameters documentation
builder.put(command, "", ParamDoc.create(subCommander.getMainParameter()));
builder.put(
command,
"",
ParamDoc.create(
subCommander.getMainParameter() == null
? null
: subCommander.getMainParameterValue()));
// For each command - go over the parameters (arguments / flags)
for (ParameterDescription parameter : subCommander.getParameters()) {
@@ -399,7 +384,7 @@ public class ShellCommand implements Command {
}
@Override
@SuppressWarnings({"unchecked", "rawtypes"})
@SuppressWarnings("unchecked")
public int complete(String buffer, int location, List completions) {
// We just defer to the other function because of the warnings (the use of a naked List by
// jline)
@@ -412,7 +397,7 @@ public class ShellCommand implements Command {
* @param buffer the command line.
* @param location the location in the command line we want to complete
* @param completions a list to fill with the completion results
* @return the number of character back from the location that are part of the completions
* @return the number of characters back from the location that are part of the completions
*/
int completeInternal(String buffer, int location, List<String> completions) {
String truncatedBuffer = buffer.substring(0, location);
@@ -453,7 +438,7 @@ public class ShellCommand implements Command {
*
* @param command the name of the command we're running. Null if not yet known (it is in 'word')
* @param context the previous argument for context. Null if we're the first.
* @param word the (partial) word to complete. Can be the command, if "command" is null, or any
* @param word the (partial) word to complete. Can be the command if "command" is null, or any
* "regular" argument, if "command" isn't null.
* @return list of all possible completions to 'word'
*/
@@ -488,19 +473,14 @@ public class ShellCommand implements Command {
}
private List<String> getCommandCompletions(String word) {
return commandFlagDocs
.rowKeySet()
.stream()
return commandFlagDocs.rowKeySet().stream()
.filter(s -> s.startsWith(word))
.map(s -> s + " ")
.collect(toImmutableList());
}
private List<String> getFlagCompletions(String command, String word) {
return commandFlagDocs
.row(command)
.keySet()
.stream()
return commandFlagDocs.row(command).keySet().stream()
.filter(s -> s.startsWith(word))
.map(s -> s + " ")
.collect(toImmutableList());
@@ -513,19 +493,15 @@ public class ShellCommand implements Command {
//
// We want documentation for a flag if the previous argument was a flag, but the value of the
// flag wasn't set. So if the previous argument is "--flag" then we want documentation of that
// flag, but if it's "--flag=value" then that flag is set and we want documentation of the
// flag, but if it's "--flag=value" then that flag is set, and we want documentation of the
// main parameters.
boolean isFlagParameter =
context != null
&& context.startsWith("-")
&& context.indexOf('=') == -1;
context != null && context.startsWith("-") && context.indexOf('=') == -1;
ParamDoc paramDoc =
Optional.ofNullable(commandFlagDocs.get(command, isFlagParameter ? context : ""))
.orElse(DEFAULT_PARAM_DOC);
if (!word.isEmpty()) {
return paramDoc
.options()
.stream()
return paramDoc.options().stream()
.filter(s -> s.startsWith(word))
.map(s -> s + " ")
.collect(toImmutableList());
@@ -548,10 +524,6 @@ public class ShellCommand implements Command {
private final byte[] prefix;
private final ByteArrayOutputStream lastLine = new ByteArrayOutputStream();
// Flag to keep track of whether the last character written was a newline. We initialize this
// to "true" because we always want the first line of output to be escaped with a leading space.
boolean lastWasNewline = true;
EncapsulatingOutputStream(OutputStream out, String identifier) {
super(out);
this.prefix = identifier.getBytes(UTF_8);
@@ -581,7 +553,7 @@ public class ShellCommand implements Command {
// (System.out)
}
/** Dump the accumulated last line of output, if there was one. */
/** Dump the accumulated last line of output if there was one. */
public void dumpLastLine() throws IOException {
if (lastLine.size() > 0) {
out.write(prefix);
@@ -35,9 +35,8 @@ public final class ParameterFactory implements IStringConverterFactory {
/** Returns JCommander converter for a given type, or {@code null} if none exists. */
@Nullable
@Override
@SuppressWarnings("unchecked")
public <T> Class<? extends IStringConverter<T>> getConverter(@Nullable Class<T> type) {
return (Class<? extends IStringConverter<T>>) CONVERTERS.get(type);
public Class<? extends IStringConverter<?>> getConverter(@Nullable Class<?> type) {
return CONVERTERS.get(type);
}
private static final ImmutableMap<Class<?>, Class<? extends IStringConverter<?>>> CONVERTERS =
@@ -53,4 +52,6 @@ public final class ParameterFactory implements IStringConverterFactory {
.put(Path.class, PathParameter.class)
.put(YearMonth.class, YearMonthParameter.class)
.build();
}
@@ -90,7 +90,7 @@ class CheckDomainClaimsCommandTest extends EppToolCommandTestCase<CheckDomainCla
@Test
void testFailure_unknownFlag() {
assertThrows(
ParameterException.class,
IllegalArgumentException.class,
() -> runCommand("--client=NewRegistrar", "--unrecognized=foo", "example.tld"));
}
}
@@ -90,7 +90,7 @@ class CheckDomainCommandTest extends EppToolCommandTestCase<CheckDomainCommand>
@Test
void testFailure_unknownFlag() {
assertThrows(
ParameterException.class,
IllegalArgumentException.class,
() -> runCommand("--client=NewRegistrar", "--unrecognized=foo", "example.tld"));
}
}
@@ -104,6 +104,12 @@ public abstract class CommandTestCase<C extends Command> {
} finally {
// Reset back to UNITTEST environment.
RegistryToolEnvironment.UNITTEST.setup(systemPropertyExtension);
// Reset the "force" field because it gets flipped every time the "--force" flag is present.
// If we force-run the same command multiple times in the same test method, the second run
// will flip the boolean again to false and not run as forced.
if (command instanceof ConfirmingCommand cc) {
cc.force = false;
}
}
}
@@ -50,8 +50,12 @@ class CreateAnchorTenantCommandTest extends EppToolCommandTestCase<CreateAnchorT
@Test
void testSuccess_multipleWordReason() throws Exception {
runCommandForced("--client=NewRegistrar", "--superuser",
"--reason=\"anchor tenant test\"", "--contact=jd1234", "--domain_name=example.tld");
runCommandForced(
"--client=NewRegistrar",
"--superuser",
"--reason=anchor tenant test",
"--contact=jd1234",
"--domain_name=example.tld");
eppVerifier
.expectSuperuser()
.verifySent("domain_create_anchor_tenant_multiple_word_reason.xml");
@@ -34,11 +34,11 @@ class CreateContactCommandTest extends EppToolCommandTestCase<CreateContactComma
runCommandForced(
"--client=NewRegistrar",
"--id=sh8013",
"--name=\"John Doe\"",
"--org=\"Example Inc.\"",
"--street=\"123 Example Dr.\"",
"--street=\"Floor 3\"",
"--street=\"Suite 100\"",
"--name=John Doe",
"--org=Example Inc.",
"--street=123 Example Dr.",
"--street=Floor 3",
"--street=Suite 100",
"--city=Dulles",
"--state=VA",
"--zip=20166-6503",
@@ -208,7 +208,7 @@ class CreateDomainCommandTest extends EppToolCommandTestCase<CreateDomainCommand
"--registrant=crr-admin",
"--admins=crr-admin",
"--techs=crr-tech",
"--reason=\"Creating test domain\"",
"--reason=Creating test domain",
"--registrar_request=false",
"example.tld");
eppVerifier.verifySent("domain_create_metadata.xml");
@@ -65,7 +65,7 @@ abstract class CreateOrUpdateReservedListCommandTestCase<
runCommandForced(
"--name=xn--q9jyb4c_common-reserved",
"--input=" + reservedTermsPath + "-nonexistent"));
assertThat(thrown).hasMessageThat().contains("-i not found");
assertThat(thrown).hasMessageThat().contains("--input not found");
}
@Test
@@ -115,15 +115,15 @@ class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarCommand>
}
@Test
void testSuccess_quotedPassword() throws Exception {
void testSuccess_password() throws Exception {
runCommandForced(
"--name=blobio",
"--password=\"some_password\"",
"--password=some_password",
"--registrar_type=REAL",
"--iana_id=8",
"--passcode=01234",
"--icann_referral_email=foo@bar.test",
"--street=\"123 Fake St\"",
"--street=123 Fake St",
"--city Fakington",
"--state MA",
"--zip 00351",
@@ -631,9 +631,9 @@ class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarCommand>
"--password=some_password",
"--registrar_type=REAL",
"--iana_id=8",
"--street=\"1234 Main St\"",
"--street \"4th Floor\"",
"--street \"Suite 1\"",
"--street=1234 Main St",
"--street 4th Floor",
"--street Suite 1",
"--city Brooklyn",
"--state NY",
"--zip 11223",
@@ -1155,7 +1155,7 @@ class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarCommand>
() ->
runCommandForced(
"--name=blobio",
"--password=\"\"",
"--password=",
"--registrar_type=REAL",
"--iana_id=8",
"--passcode=01234",
@@ -1380,7 +1380,7 @@ class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarCommand>
@Test
void testFailure_tooFewStreetLines() {
assertThrows(
IllegalArgumentException.class,
ParameterException.class,
() ->
runCommandForced(
"--name=blobio",
@@ -1580,7 +1580,7 @@ class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarCommand>
@Test
void testFailure_unknownFlag() {
assertThrows(
ParameterException.class,
IllegalArgumentException.class,
() ->
runCommandForced(
"--name=blobio",
@@ -30,8 +30,7 @@ class DeleteDomainCommandTest extends EppToolCommandTestCase<DeleteDomainCommand
@Test
void testSuccess_multipleWordReason() throws Exception {
runCommandForced(
"--client=NewRegistrar", "--domain_name=example.tld", "--reason=\"Test test\"");
runCommandForced("--client=NewRegistrar", "--domain_name=example.tld", "--reason=Test test");
eppVerifier.verifySent("domain_delete_multiple_word_reason.xml");
}
@@ -30,8 +30,7 @@ class DeleteHostCommandTest extends EppToolCommandTestCase<DeleteHostCommand> {
@Test
void testSuccess_multipleWordReason() throws Exception {
runCommand(
"--client=NewRegistrar", "--host=ns1.example.tld", "--force", "--reason=\"Test test\"");
runCommand("--client=NewRegistrar", "--host=ns1.example.tld", "--force", "--reason=Test test");
eppVerifier.verifySent("host_delete_multiple_word_reason.xml");
}
@@ -182,14 +182,18 @@ class EnqueuePollMessageCommandTest extends CommandTestCase<EnqueuePollMessageCo
void testDomainIsRequired() {
ParameterException thrown =
assertThrows(ParameterException.class, () -> runCommandForced("--message=Foo bar"));
assertThat(thrown).hasMessageThat().contains("The following option is required: -d, --domain");
assertThat(thrown)
.hasMessageThat()
.contains("The following option is required: [-d | --domain]");
}
@Test
void testMessageIsRequired() {
ParameterException thrown =
assertThrows(ParameterException.class, () -> runCommandForced("--domain=example.tld"));
assertThat(thrown).hasMessageThat().contains("The following option is required: -m, --message");
assertThat(thrown)
.hasMessageThat()
.contains("The following option is required: [-m | --message]");
}
@Test
@@ -20,6 +20,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
import com.beust.jcommander.ParameterException;
import google.registry.tools.server.ToolsTestData;
import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -85,7 +86,7 @@ class ExecuteEppCommandTest extends EppToolCommandTestCase<ExecuteEppCommand> {
@Test
void testFailure_unknownFlag() {
assertThrows(
ParameterException.class,
FileNotFoundException.class, // --unrecognized=foo is treated as the main parameter.
() -> runCommand("--client=NewRegistrar", "--unrecognized=foo", "--force", "foo.xml"));
}
}
@@ -142,8 +142,7 @@ class GenerateAllocationTokensCommandTest extends CommandTestCase<GenerateAlloca
"--discount_premiums", "true",
"--discount_years", "6",
"--token_status_transitions",
String.format(
"\"%s=NOT_STARTED,%s=VALID,%s=ENDED\"", START_OF_TIME, promoStart, promoEnd));
String.format("%s=NOT_STARTED,%s=VALID,%s=ENDED", START_OF_TIME, promoStart, promoEnd));
assertAllocationTokens(
new AllocationToken.Builder()
.setToken("promo123456789ABCDEFG")
@@ -379,8 +378,8 @@ class GenerateAllocationTokensCommandTest extends CommandTestCase<GenerateAlloca
assertThat(thrown)
.hasMessageThat()
.isEqualTo(
"Invalid value for -t parameter. Allowed values:[BULK_PRICING, DEFAULT_PROMO, PACKAGE,"
+ " SINGLE_USE, UNLIMITED_USE, REGISTER_BSA]");
"Invalid value for --type parameter. Allowed values:[BULK_PRICING, DEFAULT_PROMO,"
+ " PACKAGE, SINGLE_USE, UNLIMITED_USE, REGISTER_BSA]");
}
@Test
@@ -410,7 +409,7 @@ class GenerateAllocationTokensCommandTest extends CommandTestCase<GenerateAlloca
"--type",
"BULK_PRICING",
String.format(
"--token_status_transitions=\"%s=NOT_STARTED,%s=VALID,%s=ENDED\"",
"--token_status_transitions=%s=NOT_STARTED,%s=VALID,%s=ENDED",
START_OF_TIME, fakeClock.nowUtc(), fakeClock.nowUtc().plusDays(1)))))
.hasMessageThat()
.isEqualTo(
@@ -48,7 +48,7 @@ public class GenerateEscrowDepositCommandTest
ParameterException.class,
() ->
runCommand("--watermark=2017-01-01T00:00:00Z", "--mode=thin", "-r 42", "-o test"));
assertThat(thrown).hasMessageThat().contains("The following option is required: -t, --tld");
assertThat(thrown).hasMessageThat().contains("The following option is required: [-t | --tld]");
}
@Test
@@ -89,7 +89,7 @@ public class GenerateEscrowDepositCommandTest
() -> runCommand("--tld=tld", "--mode=full", "-r 42", "-o test"));
assertThat(thrown)
.hasMessageThat()
.contains("The following option is required: -w, --watermark");
.contains("The following option is required: [-w | --watermark]");
}
@Test
@@ -109,7 +109,9 @@ public class GenerateEscrowDepositCommandTest
() ->
runCommand(
"--tld=tld", "--watermark=2017-01-01T00:00:00Z", "--mode=thin", "-r 42"));
assertThat(thrown).hasMessageThat().contains("The following option is required: -o, --outdir");
assertThat(thrown)
.hasMessageThat()
.contains("The following option is required: [-o | --outdir]");
}
@Test
@@ -156,7 +158,7 @@ public class GenerateEscrowDepositCommandTest
"-o test"));
assertThat(thrown)
.hasMessageThat()
.contains("Invalid value for -m parameter. Allowed values:[FULL, THIN]");
.contains("Invalid value for --mode parameter. Allowed values:[FULL, THIN]");
}
@Test
@@ -205,7 +205,7 @@ class SetupOteCommandTest extends CommandTestCase<SetupOteCommand> {
"--registrar=blobio",
"--email=contact@email.com",
"--certfile=" + getCertFilename()));
assertThat(thrown).hasMessageThat().contains("option is required: -a, --ip_allow_list");
assertThat(thrown).hasMessageThat().contains("option is required: [-a | --ip_allow_list]");
}
@Test
@@ -218,7 +218,7 @@ class SetupOteCommandTest extends CommandTestCase<SetupOteCommand> {
"--ip_allow_list=1.1.1.1",
"--email=contact@email.com",
"--certfile=" + getCertFilename()));
assertThat(thrown).hasMessageThat().contains("option is required: -r, --registrar");
assertThat(thrown).hasMessageThat().contains("option is required: [-r | --registrar]");
}
@Test
@@ -244,7 +244,7 @@ class SetupOteCommandTest extends CommandTestCase<SetupOteCommand> {
"--ip_allow_list=1.1.1.1",
"--certfile=" + getCertFilename(),
"--registrar=blobio"));
assertThat(thrown).hasMessageThat().contains("option is required: --email");
assertThat(thrown).hasMessageThat().contains("option is required: [--email]");
}
@Test
@@ -51,7 +51,7 @@ class ShellCommandTest {
final SystemPropertyExtension systemPropertyExtension = new SystemPropertyExtension();
CommandRunner cli = mock(CommandRunner.class);
private FakeClock clock = new FakeClock(DateTime.parse("2000-01-01TZ"));
private final FakeClock clock = new FakeClock(DateTime.parse("2000-01-01TZ"));
private PrintStream orgStdout;
private PrintStream orgStderr;
@@ -82,7 +82,7 @@ class ShellCommandTest {
private ShellCommand createShellCommand(
CommandRunner commandRunner, Duration delay, String... commands) throws Exception {
ArrayDeque<String> queue = new ArrayDeque<String>(ImmutableList.copyOf(commands));
ArrayDeque<String> queue = new ArrayDeque<>(ImmutableList.copyOf(commands));
BufferedReader bufferedReader = mock(BufferedReader.class);
when(bufferedReader.readLine())
.thenAnswer(
@@ -241,14 +241,14 @@ class ShellCommandTest {
}
@Test
void testEncapsulatedOutputStream_basicFuncionality() throws Exception {
void testEncapsulatedOutputStream_basicFunctionality() throws Exception {
ByteArrayOutputStream backing = new ByteArrayOutputStream();
try (PrintStream out =
new PrintStream(new ShellCommand.EncapsulatingOutputStream(backing, "out: "))) {
out.println("first line");
out.print("second line\ntrailing data");
}
assertThat(backing.toString("UTF-8"))
assertThat(backing.toString(UTF_8))
.isEqualTo("out: first line\nout: second line\nout: trailing data\n");
}
@@ -256,7 +256,7 @@ class ShellCommandTest {
void testEncapsulatedOutputStream_emptyStream() throws Exception {
ByteArrayOutputStream backing = new ByteArrayOutputStream();
new PrintStream(new ShellCommand.EncapsulatingOutputStream(backing, "out: ")).close();
assertThat(backing.toString("UTF-8")).isEqualTo("");
assertThat(backing.toString(UTF_8)).isEqualTo("");
}
@Test
@@ -275,12 +275,17 @@ class ShellCommandTest {
shellCommand.encapsulateOutput = true;
shellCommand.run();
assertThat(stderr.toString("UTF-8")).isEmpty();
assertThat(stdout.toString("UTF-8"))
assertThat(stderr.toString(UTF_8)).isEmpty();
assertThat(stdout.toString(UTF_8))
.isEqualTo(
"RUNNING \"command1\"\n"
+ "out: first line\nerr: second line\nerr: surprise!\nout: fragmented line\n"
+ "SUCCESS\n");
"""
RUNNING "command1"
out: first line
err: second line
err: surprise!
out: fragmented line
SUCCESS
""");
}
@Test
@@ -295,12 +300,14 @@ class ShellCommandTest {
});
shellCommand.encapsulateOutput = true;
shellCommand.run();
assertThat(stderr.toString("UTF-8")).isEmpty();
assertThat(stdout.toString("UTF-8"))
assertThat(stderr.toString(UTF_8)).isEmpty();
assertThat(stdout.toString(UTF_8))
.isEqualTo(
"RUNNING \"command1\"\n"
+ "out: first line\n"
+ "FAILURE java.lang.Exception some error!\n");
"""
RUNNING "command1"
out: first line
FAILURE java.lang.Exception some error!
""");
}
@Test
@@ -308,16 +315,11 @@ class ShellCommandTest {
captureOutput();
ShellCommand shellCommand =
createShellCommand(
args -> {
System.out.println("first line");
},
Duration.ZERO,
"",
"do something");
args -> System.out.println("first line"), Duration.ZERO, "", "do something");
shellCommand.encapsulateOutput = true;
shellCommand.run();
assertThat(stderr.toString("UTF-8")).isEmpty();
assertThat(stdout.toString("UTF-8"))
assertThat(stderr.toString(UTF_8)).isEmpty();
assertThat(stdout.toString(UTF_8))
.isEqualTo("RUNNING \"do\" \"something\"\nout: first line\nSUCCESS\n");
}
@@ -317,7 +317,7 @@ class UpdateAllocationTokensCommandTest extends CommandTestCase<UpdateAllocation
"token",
"--token_status_transitions",
String.format(
"\"%s=NOT_STARTED,%s=VALID,%s=CANCELLED\"", START_OF_TIME, now.minusDays(1), now));
"%s=NOT_STARTED,%s=VALID,%s=CANCELLED", START_OF_TIME, now.minusDays(1), now));
token = reloadResource(token);
assertThat(token.getTokenStatusTransitions().toValueMap())
.containsExactly(START_OF_TIME, NOT_STARTED, now.minusDays(1), VALID, now, CANCELLED);
@@ -336,8 +336,7 @@ class UpdateAllocationTokensCommandTest extends CommandTestCase<UpdateAllocation
"token",
"--token_status_transitions",
String.format(
"\"%s=NOT_STARTED,%s=ENDED,%s=VALID\"",
START_OF_TIME, now.minusDays(1), now)));
"%s=NOT_STARTED,%s=ENDED,%s=VALID", START_OF_TIME, now.minusDays(1), now)));
assertThat(thrown)
.hasMessageThat()
.isEqualTo("tokenStatusTransitions map cannot transition from NOT_STARTED to ENDED.");
@@ -364,8 +363,7 @@ class UpdateAllocationTokensCommandTest extends CommandTestCase<UpdateAllocation
"--prefix",
"token",
"--token_status_transitions",
String.format(
"\"%s=NOT_STARTED,%s=VALID,%s=ENDED\"", START_OF_TIME, now.minusDays(1), now));
String.format("%s=NOT_STARTED,%s=VALID,%s=ENDED", START_OF_TIME, now.minusDays(1), now));
token = reloadResource(token);
assertThat(token.getTokenStatusTransitions().toValueMap())
.containsExactly(START_OF_TIME, NOT_STARTED, now.minusDays(1), VALID, now, ENDED);
@@ -403,8 +401,7 @@ class UpdateAllocationTokensCommandTest extends CommandTestCase<UpdateAllocation
"token",
"--token_status_transitions",
String.format(
"\"%s=NOT_STARTED,%s=VALID,%s=ENDED\"",
START_OF_TIME, now.minusDays(1), now)));
"%s=NOT_STARTED,%s=VALID,%s=ENDED", START_OF_TIME, now.minusDays(1), now)));
assertThat(thrown)
.hasMessageThat()
.isEqualTo(
@@ -213,7 +213,7 @@ class UpdateDomainCommandTest extends EppToolCommandTestCase<UpdateDomainCommand
"--client=NewRegistrar",
"--registrant=crr-admin",
"--password=2fooBAR",
"--reason=\"Testing domain update\"",
"--reason=Testing domain update",
"--registrar_request=false",
"example.tld");
eppVerifier.verifySent("domain_update_change_metadata.xml");
@@ -414,7 +414,7 @@ class UpdateRegistrarCommandTest extends CommandTestCase<UpdateRegistrarCommand>
.asBuilder()
.setBillingAccountMap(ImmutableMap.of(USD, "abc123", JPY, "789xyz"))
.build());
runCommand("--billing_account_map=\"\"", "--force", "NewRegistrar");
runCommand("--billing_account_map=", "--force", "NewRegistrar");
assertThat(loadRegistrar("NewRegistrar").getBillingAccountMap()).isEmpty();
}
@@ -482,9 +482,9 @@ class UpdateRegistrarCommandTest extends CommandTestCase<UpdateRegistrarCommand>
@Test
void testSuccess_streetAddress() throws Exception {
runCommand(
"--street=\"1234 Main St\"",
"--street \"4th Floor\"",
"--street \"Suite 1\"",
"--street=1234 Main St",
"--street 4th Floor",
"--street Suite 1",
"--city Brooklyn",
"--state NY",
"--zip 11223",
@@ -902,7 +902,7 @@ class UpdateRegistrarCommandTest extends CommandTestCase<UpdateRegistrarCommand>
@Test
void testFailure_tooFewStreetLines() {
assertThrows(
IllegalArgumentException.class,
ParameterException.class,
() ->
runCommand(
"--street",
@@ -917,7 +917,7 @@ class UpdateRegistrarCommandTest extends CommandTestCase<UpdateRegistrarCommand>
@Test
void testFailure_unknownFlag() {
assertThrows(
ParameterException.class,
IllegalArgumentException.class,
() -> runCommand("--force", "--unrecognized_flag=foo", "NewRegistrar"));
}
@@ -31,8 +31,12 @@ class UpdateServerLocksCommandTest extends EppToolCommandTestCase<UpdateServerLo
@Test
void testSuccess_multipleWordReason() throws Exception {
runCommandForced("--client=NewRegistrar", "--registrar_request=false",
"--reason=\"Test this\"", "--domain_name=example.tld", "--apply=serverRenewProhibited");
runCommandForced(
"--client=NewRegistrar",
"--registrar_request=false",
"--reason=Test this",
"--domain_name=example.tld",
"--apply=serverRenewProhibited");
eppVerifier.verifySent("update_server_locks_multiple_word_reason.xml");
}
@@ -78,7 +78,7 @@ class VerifyOteCommandTest extends CommandTestCase<VerifyOteCommand> {
@Test
void testFailure_noRegistrarsNoCheckAll() {
IllegalArgumentException thrown =
assertThrows(IllegalArgumentException.class, () -> runCommand(""));
assertThrows(IllegalArgumentException.class, () -> runCommand());
assertThat(thrown)
.hasMessageThat()
.contains("Must provide at least one registrar name, or supply --check_all with no names.");