How to use DescribedOption class of org.openqa.selenium.grid.config package

Best Selenium code snippet using org.openqa.selenium.grid.config.DescribedOption

Run Selenium automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

copy
1// Licensed to the Software Freedom Conservancy (SFC) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The SFC licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18package org.openqa.selenium.grid.commands;
19
20import com.beust.jcommander.JCommander;
21import com.beust.jcommander.ParameterException;
22import com.beust.jcommander.Parameters;
23import com.beust.jcommander.internal.DefaultConsole;
24import com.google.auto.service.AutoService;
25import org.openqa.selenium.cli.CliCommand;
26import org.openqa.selenium.grid.config.DescribedOption;
27import org.openqa.selenium.grid.config.Role;
28import org.openqa.selenium.grid.server.HelpFlags;
29
30import java.io.PrintStream;
31import java.util.AbstractMap;
32import java.util.Collections;
33import java.util.Comparator;
34import java.util.Map;
35import java.util.ServiceLoader;
36import java.util.Set;
37import java.util.stream.Collectors;
38import java.util.stream.StreamSupport;
39
40import static java.util.stream.Collectors.joining;
41import static org.openqa.selenium.grid.config.StandardGridRoles.ALL_ROLES;
42
43@AutoService(CliCommand.class)
44public class CompletionCommand implements CliCommand {
45  @Override
46  public String getName() {
47    return "completion";
48  }
49
50  @Override
51  public String getDescription() {
52    return "Generate shell autocompletions";
53  }
54
55  @Override
56  public Set<Role> getConfigurableRoles() {
57    return ALL_ROLES;
58  }
59
60  @Override
61  public Set<Object> getFlagObjects() {
62    return Collections.singleton(new HelpFlags());
63  }
64
65  @Override
66  public Executable configure(PrintStream out, PrintStream err, String... args) {
67    HelpFlags help = new HelpFlags();
68
69    Zsh zsh = new Zsh();
70
71    JCommander commander = JCommander.newBuilder()
72      .programName("selenium")
73      .addObject(help)
74      .addCommand(zsh)
75      .build();
76    commander.setConsole(new DefaultConsole(out));
77
78    return () -> {
79      try {
80        commander.parse(args);
81      } catch (ParameterException e) {
82        err.println(e.getMessage());
83        commander.usage();
84        return;
85      }
86
87      if (help.displayHelp(commander, out)) {
88        return;
89      }
90
91      if (args.length == 0) {
92        commander.parse();
93      }
94
95      switch (commander.getParsedCommand()) {
96        case "zsh":
97          outputZshCompletions(out);
98          break;
99
100        default:
101          err.println("Unrecognised shell: " + commander.getParsedCommand());
102          System.exit(1);
103          break;
104      }
105    };
106  }
107
108  private void outputZshCompletions(PrintStream out) {
109    Map<CliCommand, Set<DescribedOption>> allCommands = listKnownCommands();
110
111    // My kingdom for multiline strings
112    out.println("#compdef selenium");
113    out.println("local context state state_descr line");
114    out.println("typeset -A opt_args");
115    out.println("_selenium() {");
116    out.println("  _arguments -C \\");
117    out.println("    '(- :)--ext[Amend the classpath for Grid]: :->arg' \\");
118    out.println("    '(-): :->command' \\");
119    out.println("    '(-)*:: :->arg' && return");
120    out.println("  case $state in");
121    out.println("    (command)");
122    out.println("      local cmds");
123    out.println("      cmds=(");
124
125    allCommands.keySet().stream()
126      .sorted(Comparator.comparing(CliCommand::getName))
127      .forEach(cmd -> {
128        out.println(String.format("        '%s:%s'", cmd.getName(), cmd.getDescription().replace("'", "\\'")));
129      });
130
131    out.println("      )");
132    out.println("      _describe 'commands' cmds");
133    out.println("      ;;");
134    out.println("    (arg)");
135    out.println("      case ${words[1]} in");
136
137    allCommands.keySet().stream()
138      .sorted(Comparator.comparing(CliCommand::getName))
139      .forEach(cmd -> {
140        String shellName = cmd.getName().replace('-', '_');
141        out.println(String.format("        (%s)", cmd.getName()));
142        out.println(String.format("          _selenium_%s", shellName));
143        out.println("          ;;");
144      });
145
146    out.println("      esac");
147    out.println("      ;;");
148    out.println("  esac");
149    out.println("}\n\n");
150
151    allCommands.forEach((cmd, options) -> {
152      out.println(String.format("_selenium_%s() {", cmd.getName().replace('-', '_')));
153      out.println("  args=(");
154
155      options.stream()
156        .filter(opt -> !opt.flags().isEmpty())
157        .sorted(Comparator.comparing(opt -> opt.flags().iterator().next()))
158        .forEach(opt -> {
159          String quotedDesc = opt.description.replace("'", "\\''").replace(":", "\\:");
160
161          if (opt.flags().size() == 1) {
162            out.println(String.format("    '%s[%s]%s'", opt.flags().iterator().next(), quotedDesc, getZshType(opt)));
163          } else {
164            out.print("    '");
165            out.print(opt.flags.stream().collect(joining(" ", "(", ")")));
166            out.print("'");
167            out.print(opt.flags.stream().collect(joining(",", "{", "}")));
168            out.print("'");
169            out.print(String.format("[%s]", quotedDesc));
170            out.print(getZshType(opt));
171            out.print("'\n");
172          }
173        });
174
175      out.println("  )");
176      out.println("  _arguments $args && return");
177      out.println("}\n\n");
178    });
179
180    out.println("_selenium");
181  }
182
183  private String getZshType(DescribedOption option) {
184    switch (option.type) {
185      case "boolean":
186        return ":(true false)";
187
188      case "int":
189        return ":int";
190
191      case "list of strings":
192      case "string":
193        return ": ";
194
195      case "uri":
196      case "url":
197        return ":urls: ";
198
199      case "path":
200        return ":filename:_files";
201
202      default:
203        throw new IllegalStateException("Unknown type: " + option.type);
204    }
205  }
206
207  private Map<CliCommand, Set<DescribedOption>> listKnownCommands() {
208    return StreamSupport.stream(ServiceLoader.load(CliCommand.class).spliterator(), true)
209      .map(command -> new AbstractMap.SimpleEntry<>(
210        command,
211        DescribedOption.findAllMatchingOptions(command.getConfigurableRoles())))
212      .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
213  }
214
215  @Parameters(commandNames = "zsh", commandDescription = "Create autocompletions for zsh")
216  private static class Zsh {}
217}
218
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

...Most popular Stackoverflow questions on DescribedOption

    No relevant questions found for this class 😞

Run Selenium Automation Tests on LambdaTest Cloud Grid

Trigger Selenium automation tests on a cloud-based Grid of 3000+ real browsers and operating systems.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)