(runner)
| 142 | |
| 143 | |
| 144 | def test_custom_parser(runner): |
| 145 | import optparse |
| 146 | |
| 147 | @click.group() |
| 148 | def cli(): |
| 149 | pass |
| 150 | |
| 151 | class OptParseCommand(click.Command): |
| 152 | def __init__(self, name, parser, callback): |
| 153 | super().__init__(name) |
| 154 | self.parser = parser |
| 155 | self.callback = callback |
| 156 | |
| 157 | def parse_args(self, ctx, args): |
| 158 | try: |
| 159 | opts, args = parser.parse_args(args) |
| 160 | except Exception as e: |
| 161 | ctx.fail(str(e)) |
| 162 | ctx.args = args |
| 163 | ctx.params = vars(opts) |
| 164 | |
| 165 | def get_usage(self, ctx): |
| 166 | return self.parser.get_usage() |
| 167 | |
| 168 | def get_help(self, ctx): |
| 169 | return self.parser.format_help() |
| 170 | |
| 171 | def invoke(self, ctx): |
| 172 | ctx.invoke(self.callback, ctx.args, **ctx.params) |
| 173 | |
| 174 | parser = optparse.OptionParser(usage="Usage: foo test [OPTIONS]") |
| 175 | parser.add_option( |
| 176 | "-f", "--file", dest="filename", help="write report to FILE", metavar="FILE" |
| 177 | ) |
| 178 | parser.add_option( |
| 179 | "-q", |
| 180 | "--quiet", |
| 181 | action="store_false", |
| 182 | dest="verbose", |
| 183 | default=True, |
| 184 | help="don't print status messages to stdout", |
| 185 | ) |
| 186 | |
| 187 | def test_callback(args, filename, verbose): |
| 188 | click.echo(" ".join(args)) |
| 189 | click.echo(filename) |
| 190 | click.echo(verbose) |
| 191 | |
| 192 | cli.add_command(OptParseCommand("test", parser, test_callback)) |
| 193 | |
| 194 | result = runner.invoke(cli, ["test", "-f", "f.txt", "-q", "q1.txt", "q2.txt"]) |
| 195 | assert result.exception is None |
| 196 | assert result.output.splitlines() == ["q1.txt q2.txt", "f.txt", "False"] |
| 197 | |
| 198 | result = runner.invoke(cli, ["test", "--help"]) |
| 199 | assert result.exception is None |
| 200 | assert result.output.splitlines() == [ |
| 201 | "Usage: foo test [OPTIONS]", |
nothing calls this directly
no test coverage detected