[Bash] Bash client script generator (#4541)

* Initial commit

* Remormatted petstore tests

* Added Bash codegen to main README.md

* Added bash to integration tests

* Fixed stdin detection in generated script

* Added back ruby module
This commit is contained in:
Bartek Kryza
2017-01-12 09:48:25 +01:00
committed by wing328
parent 2e4de0ca1e
commit 0fb154e9a2
24 changed files with 8338 additions and 1 deletions

View File

@@ -0,0 +1,23 @@
# Swagger Codegen Ignore
# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen
# Use this file to prevent files from being overwritten by the generator.
# The patterns follow closely to .gitignore or .dockerignore.
# As an example, the C# client generator defines ApiClient.cs.
# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line:
#ApiClient.cs
# You can match any string of characters against a directory, file or extension with a single asterisk (*):
#foo/*/qux
# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux
# You can recursively match patterns against a directory, file or extension with a double asterisk (**):
#foo/**/qux
# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux
# You can also negate patterns with an exclamation (!).
# For example, you can ignore all files in a docs folder with the file extension .md:
#docs/*.md
# Then explicitly reverse the ignore rule for a single file:
#!docs/README.md

View File

@@ -0,0 +1,75 @@
# Swagger Petstore Bash client
## Overview
This is a Bash client script for accessing Swagger Petstore service.
The script uses cURL underneath for making all REST calls.
## Usage
```shell
# Make sure the script has executable rights
$ chmod u+x petstore-cli
# Print the list of operations available on the service
$ ./petstore-cli -h
# Print the service description
$ ./petstore-cli --about
# Print detailed information about specific operation
$ ./petstore-cli <operationId> -h
# Make GET request
./petstore-cli --host http://<hostname>:<port> --accept xml <operationId> <queryParam1>=<value1> <header_key1>:<header_value2>
# Make GET request using arbitrary curl options (must be passed before <operationId>) to an SSL service using username:password
petstore-cli -k -sS --tlsv1.2 --host https://<hostname> -u <user>:<password> --accept xml <operationId> <queryParam1>=<value1> <header_key1>:<header_value2>
# Make POST request
$ echo '<body_content>' | petstore-cli --host <hostname> --content-type json <operationId> -
# Make POST request with simple JSON content, e.g.:
# {
# "key1": "value1",
# "key2": "value2",
# "key3": 23
# }
$ echo '<body_content>' | petstore-cli --host <hostname> --content-type json <operationId> key1==value1 key2=value2 key3:=23 -
# Preview the cURL command without actually executing it
$ petstore-cli --host http://<hostname>:<port> --dry-run <operationid>
```
## Shell completion
### Bash
The generated bash-completion script can be either directly loaded to the current Bash session using:
```shell
source petstore-cli.bash-completion
```
Alternatively, the script can be copied to the `/etc/bash-completion.d` (or on OSX with Homebrew to `/usr/local/etc/bash-completion.d`):
```shell
sudo cp petstore-cli.bash-completion /etc/bash-completion.d/petstore-cli
```
#### OS X
On OSX you might need to install bash-completion using Homebrew:
```shell
brew install bash-completion
```
and add the following to the `~/.bashrc`:
```shell
if [ -f $(brew --prefix)/etc/bash_completion ]; then
. $(brew --prefix)/etc/bash_completion
fi
```
### Zsh
In Zsh, the generated `_petstore-cli` Zsh completion file must be copied to one of the folders under `$FPATH` variable.

View File

@@ -0,0 +1,454 @@
#compdef petstore-cli
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# !
# ! Note:
# !
# ! THIS SCRIPT HAS BEEN AUTOMATICALLY GENERATED USING
# ! swagger-codegen (https://github.com/swagger-api/swagger-codegen)
# ! FROM SWAGGER SPECIFICATION IN JSON.
# !
# ! Based on: https://github.com/Valodim/zsh-curl-completion/blob/master/_curl
# !
# ! Generated on: 2017-01-12T00:07:27.471+01:00
# !
# !
# ! Installation:
# !
# ! Copy the _petstore-cli file to any directory under FPATH
# ! environment variable (echo $FPATH)
# !
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
local curcontext="$curcontext" state line ret=1
typeset -A opt_args
#
# cURL crypto engines completion function
#
_curl_crypto_engine() {
local vals
vals=( ${${(f)"$(curl --engine list)":gs/ /}[2,$]} )
_describe -t outputs 'engines' vals && return 0
}
#
# cURL post data completion functions=
#
_curl_post_data() {
# don't do anything further if this is raw content
compset -P '=' && _message 'raw content' && return 0
# complete filename or stdin for @ syntax
compset -P '*@' && {
local expl
_description files expl stdin
compadd "$expl[@]" - "-"
_files
return 0
}
# got a name already? expecting data.
compset -P '*=' && _message 'data value' && return 0
# otherwise, name (or @ or =) should be specified
_message 'data name' && return 0
}
local arg_http arg_ftp arg_other arg_proxy arg_crypto arg_connection arg_auth arg_input arg_output
# HTTP Arguments
arg_http=(''\
{-0,--http1.0}'[force use of use http 1.0 instead of 1.1]' \
{-b,--cookie}'[pass data to http server as cookie]:data or file' \
{-c,--cookie-jar}'[specify cookie file]:file name:_files' \
{-d,--data}'[send specified data as HTTP POST data]:data:{_curl_post_data}' \
'--data-binary[post HTTP POST data without any processing]:data:{_curl_post_data}' \
'--data-urlencode[post HTTP POST data, with url encoding]:data:{_curl_post_data}' \
{-f,--fail}'[enable failfast behavior for server errors]' \
'*'{-F,--form}'[add POST form data]:name=content' \
{-G,--get}'[use HTTP GET even with data (-d, --data, --data-binary)]' \
'*'{-H,--header}'[specify an extra header]:header' \
'--ignore-content-length[ignore Content-Length header]' \
{-i,--include}'[include HTTP header in the output]' \
{-j,--junk-session-cookies}'[discard all session cookies]' \
{-e,--referer}'[send url as referer]:referer url:_urls' \
{-L,--location}'[follow Location headers on http 3XX response]' \
'--location-trusted[like --location, but allows sending of auth data to redirected hosts]' \
'--max-redirs[set maximum number of redirection followings allowed]:number' \
{-J,--remote-header-name}'[use Content-Disposition for output file name]' \
{-O,--remote-name}'[write to filename parsed from url instead of stdout]' \
'--post301[do not convert POST to GET after following 301 Location response (follow RFC 2616/10.3.2)]' \
'--post302[do not convert POST to GET after following 302 Location response (follow RFC 2616/10.3.2)]' \
)
# FTP arguments
arg_ftp=(\
{-a,--append}'[append to target file instead of overwriting (FTP/SFTP)]' \
'--crlf[convert LF to CRLF in upload]' \
'--disable-eprt[disable use of EPRT and LPRT for active FTP transfers]' \
'--disable-epsv[disable use of EPSV for passive FTP transfers]' \
'--ftp-account[account data (FTP)]:data' \
'--ftp-alternative-to-user[command to send when USER and PASS commands fail (FTP)]:command' \
'--ftp-create-dirs[create paths remotely if it does not exist]' \
'--ftp-method[ftp method to use to reach a file (FTP)]:method:(multicwd ocwd singlecwd)' \
'--ftp-pasv[use passive mode for the data connection (FTP)]' \
'--ftp-skip-pasv-ip[do not use the ip the server suggests for PASV]' \
'--form-string[like --form, but do not parse content]:name=string' \
'--ftp-pret[send PRET before PASV]' \
'--ftp-ssl-ccc[use clear command channel (CCC) after authentication (FTP)]' \
'--ftp-ssl-ccc-mode[sets the CCC mode (FTP)]:mode:(active passive)' \
'--ftp-ssl-control[require SSL/TLS for FTP login, clear for transfer]' \
{-l,--list-only}'[list names only when listing directories (FTP)]' \
{-P,--ftp-port}'[use active mode, tell server to connect to specified address or interface (FTP]:address' \
'*'{-Q,--quote}'[send arbitrary command to the remote server before transfer (FTP/SFTP)]:command' \
)
# Other Protocol arguments
arg_other=(\
'--mail-from[specify From: address]:address' \
'--mail-rcpt[specify email recipient for SMTP, may be given multiple times]:address' \
{-t,--telnet-option}'[pass options to telnet protocol]:opt=val' \
'--tftp-blksize[set tftp BLKSIZE option]:value' \
)
# Proxy arguments
arg_proxy=(\
'--noproxy[list of hosts to connect directly to instead of through proxy]:no-proxy-list' \
{-p,--proxytunnel}'[tunnel non-http protocols through http proxy]' \
{-U,--proxy-user}'[specify the user name and password to use for proxy authentication]:user:password' \
'--proxy-anyauth[use any authentication method for proxy, default to most secure]' \
'--proxy-basic[use HTTP Basic authentication for proxy]' \
'--proxy-digest[use http digest authentication for proxy]' \
'--proxy-negotiate[enable GSS-Negotiate authentication for proxy]' \
'--proxy-ntlm[enable ntlm authentication for proxy]' \
'--proxy1.0[use http 1.0 proxy]:proxy url' \
{-x,--proxy}'[use specified proxy]:proxy url' \
'--socks5-gssapi-service[change service name for socks server]:servicename' \
'--socks5-gssapi-nec[allow unprotected exchange of protection mode negotiation]' \
)
# Crypto arguments
arg_crypto=(\
{-1,--tlsv1}'[Forces curl to use TLS version 1 when negotiating with a remote TLS server.]' \
{-2,--sslv2}'[Forces curl to use SSL version 2 when negotiating with a remote SSL server.]' \
{-3,--sslv3}'[Forces curl to use SSL version 3 when negotiating with a remote SSL server.]' \
'--ciphers[specifies which cipher to use for the ssl connection]:list of ciphers' \
'--crlfile[specify file with revoked certificates]:file' \
'--delegation[set delegation policy to use with GSS/kerberos]:delegation policy:(none policy always)' \
{-E,--cert}'[use specified client certificate]:certificate file:_files' \
'--engine[use selected OpenSSL crypto engine]:ssl crypto engine:{_curl_crypto_engine}' \
'--egd-file[set ssl entropy gathering daemon socket]:entropy socket:_files' \
'--cert-type[specify certificate type (PEM, DER, ENG)]:certificate type:(PEM DER ENG)' \
'--cacert[specify certificate file to verify the peer with]:CA certificate:_files' \
'--capath[specify a search path for certificate files]:CA certificate directory:_directories' \
'--hostpubmd5[check remote hosts public key]:md5 hash' \
{-k,--insecure}'[allow ssl to perform insecure ssl connections (ie, ignore certificate)]' \
'--key[ssl/ssh private key file name]:key file:_files' \
'--key-type[ssl/ssh private key file type]:file type:(PEM DER ENG)' \
'--pubkey[ssh public key file]:pubkey file:_files' \
'--random-file[set source of random data for ssl]:random source:_files' \
'--no-sessionid[disable caching of ssl session ids]' \
'--pass:phrase[passphrase for ssl/ssh private key]' \
'--ssl[try to use ssl/tls for connection, if available]' \
'--ssl-reqd[try to use ssl/tls for connection, fail if unavailable]' \
'--tlsauthtype[set TLS authentication type (only SRP supported!)]:authtype' \
'--tlsuser[set username for TLS authentication]:user' \
'--tlspassword[set password for TLS authentication]:password' \
)
# Connection arguments
arg_connection=(\
{-4,--ipv4}'[prefer ipv4]' \
{-6,--ipv6}'[prefer ipv6, if available]' \
{-B,--use-ascii}'[use ascii mode]' \
'--compressed[request a compressed transfer]' \
'--connect-timeout[timeout for connection phase]:seconds' \
{-I,--head}'[fetch http HEAD only (HTTP/FTP/FILE]' \
'--interface[work on a specific interface]:name' \
'--keepalive-time[set time to wait before sending keepalive probes]:seconds' \
'--limit-rate[specify maximum transfer rate]:speed' \
'--local-port[set preferred number or range of local ports to use]:num' \
{-N,--no-buffer}'[disable buffering of the output stream]' \
'--no-keepalive[disable use of keepalive messages in TCP connections]' \
'--raw[disable all http decoding and pass raw data]' \
'--resolve[provide a custom address for a specific host and port pair]:host\:port\:address' \
'--retry[specify maximum number of retries for transient errors]:num' \
'--retry-delay[specify delay between retries]:seconds' \
'--retry-max-time[maximum time to spend on retries]:seconds' \
'--tcp-nodelay[turn on TCP_NODELAY option]' \
{-y,--speed-time}'[specify time to abort after if download is slower than speed-limit]:time' \
{-Y,--speed-limit}'[specify minimum speed for --speed-time]:speed' \
)
# Authentication arguments
arg_auth=(\
'--anyauth[use any authentication method, default to most secure]' \
'--basic[use HTTP Basic authentication]' \
'--ntlm[enable ntlm authentication]' \
'--digest[use http digest authentication]' \
'--krb[use kerberos authentication]:auth:(clear safe confidential private)' \
'--negotiate[enable GSS-Negotiate authentication]' \
{-n,--netrc}'[scan ~/.netrc for login data]' \
'--netrc-optional[like --netrc, but does not make .netrc usage mandatory]' \
'--netrc-file[like --netrc, but specify file to use]:netrc file:_files' \
'--tr-encoding[request compressed transfer-encoding]' \
{-u,--user}'[specify user name and password for server authentication]:user\:password' \
)
# Input arguments
arg_input=(\
{-C,--continue-at}'[resume at offset ]:offset' \
{-g,--globoff}'[do not glob {}\[\] letters]' \
'--max-filesize[maximum filesize to download, fail for bigger files]:bytes' \
'--proto[specify allowed protocols for transfer]:protocols' \
'--proto-redir[specify allowed protocols for transfer after a redirect]:protocols' \
{-r,--range}'[set range of bytes to request (HTTP/FTP/SFTP/FILE)]:range' \
{-R,--remote-time}'[use timestamp of remote file for local file]' \
{-T,--upload-file}'[transfer file to remote url (using PUT for HTTP)]:file to upload:_files' \
'--url[specify a URL to fetch (multi)]:url:_urls' \
{-z,--time-cond}'[request downloaded file to be newer than date or given reference file]:date expression' \
)
# Output arguments
arg_output=(\
'--create-dirs[create local directory hierarchy as needed]' \
{-D,--dump-header}'[write protocol headers to file]:dump file:_files' \
{-o,--output}'[write to specified file instead of stdout]:output file:_files' \
{--progress-bar,-\#}'[display progress as a simple progress bar]' \
{-\#,--progress-bar}'[Make curl display progress as a simple progress bar instead of the standard, more informational, meter.]' \
{-R,--remote-time}'[use timestamp of remote file for local file]' \
'--raw[disable all http decoding and pass raw data]' \
{-s,--silent}'[silent mode, do not show progress meter or error messages]' \
{-S,--show-error}'[show errors in silent mode]' \
'--stderr[redirect stderr to specified file]:output file:_files' \
'--trace[enable full trace dump of all incoming and outgoing data]:trace file:_files' \
'--trace-ascii[enable full trace dump of all incoming and outgoing data, without hex data]:trace file:_files' \
'--trace-time[prepends a time stamp to each trace or verbose line that curl displays]' \
{-v,--verbose}'[output debug info]' \
{-w,--write-out}'[specify message to output on successful operation]:format string' \
'--xattr[store some file metadata in extended file attributes]' \
{-X,--request}'[specifies request method for HTTP server]:method:(GET POST PUT DELETE HEAD OPTIONS TRACE CONNECT PATCH LINK UNLINK)' \
)
_arguments -C -s $arg_http $arg_ftp $arg_other $arg_crypto $arg_connection $arg_auth $arg_input $arg_output \
{-M,--manual}'[print manual]' \
'*'{-K,--config}'[use other config file to read arguments from]:config file:_files' \
'--libcurl[output libcurl code for the operation to file]:output file:_files' \
{-m,--max-time}'[limit total time of operation]:seconds' \
{-s,--silent}'[silent mode, do not show progress meter or error messages]' \
{-S,--show-error}'[show errors in silent mode]' \
'--stderr[redirect stderr to specified file]:output file:_files' \
'-q[do not read settings from .curlrc (must be first option)]' \
{-h,--help}'[Print help and list of operations]' \
{-V,--version}'[Print service API version]' \
'--about[Print the information about service]' \
'--host[Specify the host URL]':URL:_urls \
'--dry-run[Print out the cURL command without executing it]' \
{-ac,--accept}'[Set the 'Accept' header in the request]' \
{-ct,--content-type}'[Set the 'Content-type' header in request]' \
'1: :->ops' \
'*:: :->args' \
&& ret=0
case $state in
ops)
# Operations
_values "Operations" \
"testClientModel[To test \"client\" model]" \
"testEndpointParameters[Fake endpoint for testing various parameters
假端點
偽のエンドポイント
가짜 엔드 포인트]" \
"testEnumParameters[To test enum parameters]" "addPet[Add a new pet to the store]" \
"deletePet[Deletes a pet]" \
"findPetsByStatus[Finds Pets by status]" \
"findPetsByTags[Finds Pets by tags]" \
"getPetById[Find pet by ID]" \
"updatePet[Update an existing pet]" \
"updatePetWithForm[Updates a pet in the store with form data]" \
"uploadFile[uploads an image]" "deleteOrder[Delete purchase order by ID]" \
"getInventory[Returns pet inventories by status]" \
"getOrderById[Find purchase order by ID]" \
"placeOrder[Place an order for a pet]" "createUser[Create user]" \
"createUsersWithArrayInput[Creates list of users with given input array]" \
"createUsersWithListInput[Creates list of users with given input array]" \
"deleteUser[Delete user]" \
"getUserByName[Get user by user name]" \
"loginUser[Logs user into the system]" \
"logoutUser[Logs out current logged in user session]" \
"updateUser[Updated user]"
_arguments "(--help)--help[Print information about operation]"
ret=0
;;
args)
case $line[1] in
testClientModel)
local -a _op_arguments
_op_arguments=(
)
_describe -t actions 'operations' _op_arguments && ret=0
;;
testEndpointParameters)
local -a _op_arguments
_op_arguments=(
)
_describe -t actions 'operations' _op_arguments && ret=0
;;
testEnumParameters)
local -a _op_arguments
_op_arguments=(
"enum_query_string_array=:Query parameter enum test (string array)"
"enum_query_string=:Query parameter enum test (string)"
"enum_query_integer=:Query parameter enum test (double)"
"enum_header_string_array\::Header parameter enum test (string array)"
"enum_header_string\::Header parameter enum test (string)"
)
_describe -t actions 'operations' _op_arguments && ret=0
;;
addPet)
local -a _op_arguments
_op_arguments=(
)
_describe -t actions 'operations' _op_arguments && ret=0
;;
deletePet)
local -a _op_arguments
_op_arguments=(
"petId=:Pet id to delete"
"api_key\::"
)
_describe -t actions 'operations' _op_arguments && ret=0
;;
findPetsByStatus)
local -a _op_arguments
_op_arguments=(
"status=:Status values that need to be considered for filter"
)
_describe -t actions 'operations' _op_arguments && ret=0
;;
findPetsByTags)
local -a _op_arguments
_op_arguments=(
"tags=:Tags to filter by"
)
_describe -t actions 'operations' _op_arguments && ret=0
;;
getPetById)
local -a _op_arguments
_op_arguments=(
"petId=:ID of pet to return"
)
_describe -t actions 'operations' _op_arguments && ret=0
;;
updatePet)
local -a _op_arguments
_op_arguments=(
)
_describe -t actions 'operations' _op_arguments && ret=0
;;
updatePetWithForm)
local -a _op_arguments
_op_arguments=(
"petId=:ID of pet that needs to be updated"
)
_describe -t actions 'operations' _op_arguments && ret=0
;;
uploadFile)
local -a _op_arguments
_op_arguments=(
"petId=:ID of pet to update"
)
_describe -t actions 'operations' _op_arguments && ret=0
;;
deleteOrder)
local -a _op_arguments
_op_arguments=(
"orderId=:ID of the order that needs to be deleted"
)
_describe -t actions 'operations' _op_arguments && ret=0
;;
getInventory)
local -a _op_arguments
_op_arguments=(
)
_describe -t actions 'operations' _op_arguments && ret=0
;;
getOrderById)
local -a _op_arguments
_op_arguments=(
"orderId=:ID of pet that needs to be fetched"
)
_describe -t actions 'operations' _op_arguments && ret=0
;;
placeOrder)
local -a _op_arguments
_op_arguments=(
)
_describe -t actions 'operations' _op_arguments && ret=0
;;
createUser)
local -a _op_arguments
_op_arguments=(
)
_describe -t actions 'operations' _op_arguments && ret=0
;;
createUsersWithArrayInput)
local -a _op_arguments
_op_arguments=(
)
_describe -t actions 'operations' _op_arguments && ret=0
;;
createUsersWithListInput)
local -a _op_arguments
_op_arguments=(
)
_describe -t actions 'operations' _op_arguments && ret=0
;;
deleteUser)
local -a _op_arguments
_op_arguments=(
"username=:The name that needs to be deleted"
)
_describe -t actions 'operations' _op_arguments && ret=0
;;
getUserByName)
local -a _op_arguments
_op_arguments=(
"username=:The name that needs to be fetched. Use user1 for testing."
)
_describe -t actions 'operations' _op_arguments && ret=0
;;
loginUser)
local -a _op_arguments
_op_arguments=(
"username=:The user name for login"
"password=:The password for login in clear text"
)
_describe -t actions 'operations' _op_arguments && ret=0
;;
logoutUser)
local -a _op_arguments
_op_arguments=(
)
_describe -t actions 'operations' _op_arguments && ret=0
;;
updateUser)
local -a _op_arguments
_op_arguments=(
"username=:name that need to be deleted"
)
_describe -t actions 'operations' _op_arguments && ret=0
;;
esac
;;
esac
return ret

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,286 @@
# petstore-cli completion -*- shell-script -*-
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# !
# ! Note:
# !
# ! THIS SCRIPT HAS BEEN AUTOMATICALLY GENERATED USING
# ! swagger-codegen (https://github.com/swagger-api/swagger-codegen)
# ! FROM SWAGGER SPECIFICATION IN JSON.
# !
# ! Generated on: 2017-01-12T00:07:27.471+01:00
# !
# !
# ! System wide installation:
# !
# ! $ sudo cp petstore-cli.bash-completion /etc/bash-completion.d/petstore-cli
# !
# !
# ! User home installation (add this line to .bash_profile):
# !
# ! [ -r ~/petstore-cli.bash-completion ] && source ~/petstore-cli.bash-completion
# !
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
declare -A mime_type_abbreviations
# text/*
mime_type_abbreviations["text"]="text/plain"
mime_type_abbreviations["html"]="text/html"
mime_type_abbreviations["md"]="text/x-markdown"
mime_type_abbreviations["csv"]="text/csv"
mime_type_abbreviations["css"]="text/css"
mime_type_abbreviations["rtf"]="text/rtf"
# application/*
mime_type_abbreviations["json"]="application/json"
mime_type_abbreviations["xml"]="application/xml"
mime_type_abbreviations["yaml"]="application/yaml"
mime_type_abbreviations["js"]="application/javascript"
mime_type_abbreviations["bin"]="application/octet-stream"
mime_type_abbreviations["rdf"]="application/rdf+xml"
# image/*
mime_type_abbreviations["jpg"]="image/jpeg"
mime_type_abbreviations["png"]="image/png"
mime_type_abbreviations["gif"]="image/gif"
mime_type_abbreviations["bmp"]="image/bmp"
mime_type_abbreviations["tiff"]="image/tiff"
__osx_init_completion()
{
COMPREPLY=()
_get_comp_words_by_ref cur prev words cword
}
_petstore-cli()
{
local cur
local prev
local words
local cword
#words="${COMP_WORDS}"
#cword="${COMP_CWORD}"
#prev="${COMP_WORDS[COMP_CWORD-1]}"
#cur="${COMP_WORDS[COMP_CWORD]}"
# The reference of currently selected REST operation
local operation=""
# The list of available operation in the REST service
# It's modelled as an associative array for efficient key lookup
declare -A operations
operations["testClientModel"]=1
operations["testEndpointParameters"]=1
operations["testEnumParameters"]=1
operations["addPet"]=1
operations["deletePet"]=1
operations["findPetsByStatus"]=1
operations["findPetsByTags"]=1
operations["getPetById"]=1
operations["updatePet"]=1
operations["updatePetWithForm"]=1
operations["uploadFile"]=1
operations["deleteOrder"]=1
operations["getInventory"]=1
operations["getOrderById"]=1
operations["placeOrder"]=1
operations["createUser"]=1
operations["createUsersWithArrayInput"]=1
operations["createUsersWithListInput"]=1
operations["deleteUser"]=1
operations["getUserByName"]=1
operations["loginUser"]=1
operations["logoutUser"]=1
operations["updateUser"]=1
# An associative array of operations to their parameters
# Only include path, query and header parameters
declare -A operation_parameters
operation_parameters["testClientModel"]=""
operation_parameters["testEndpointParameters"]=""
operation_parameters["testEnumParameters"]="enum_query_string_array= enum_query_string= enum_query_integer= enum_header_string_array: enum_header_string: "
operation_parameters["addPet"]=""
operation_parameters["deletePet"]="petId= api_key: "
operation_parameters["findPetsByStatus"]="status= "
operation_parameters["findPetsByTags"]="tags= "
operation_parameters["getPetById"]="petId= "
operation_parameters["updatePet"]=""
operation_parameters["updatePetWithForm"]="petId= "
operation_parameters["uploadFile"]="petId= "
operation_parameters["deleteOrder"]="orderId= "
operation_parameters["getInventory"]=""
operation_parameters["getOrderById"]="orderId= "
operation_parameters["placeOrder"]=""
operation_parameters["createUser"]=""
operation_parameters["createUsersWithArrayInput"]=""
operation_parameters["createUsersWithListInput"]=""
operation_parameters["deleteUser"]="username= "
operation_parameters["getUserByName"]="username= "
operation_parameters["loginUser"]="username= password= "
operation_parameters["logoutUser"]=""
operation_parameters["updateUser"]="username= "
# An associative array of possible values for enum parameters
declare -A operation_parameters_enum_values
#
# Check if the _init_completion function is available, which is
# available since bash-completion 1.4
#
if declare -F _init_completions >/dev/null 2>&1; then
_init_completion -s || return
else
__osx_init_completion || return
fi
# Check if operation is already in the command line provided
for word in "${words[@]}"; do
if [[ -n $word && ${operations[$word]} ]]; then
operation="${word}"
fi
done
if [[ -z $operation ]]; then
case $prev in
--ciphers|--connect-timeout|-C|--continue-at|-F|--form|--form-string|\
--ftp-account|--ftp-alternative-to-user|-P|--ftp-port|-H|--header|-h|\
--help|--hostpubmd5|--keepalive-time|--krb|--limit-rate|--local-port|\
--mail-from|--mail-rcpt|--max-filesize|--max-redirs|-m|--max-time|\
--pass|--proto|--proto-redir|--proxy-user|--proxy1.0|-Q|--quote|-r|\
--range|-X|--request|--retry|--retry-delay|--retry-max-time|\
--socks5-gssapi-service|-t|--telnet-option|--tftp-blksize|-z|\
--time-cond|--url|-u|--user|-A|--user-agent|-V|--version|-w|\
--write-out|--resolve|--tlsuser|--tlspassword|--about)
return
;;
-K|--config|-b|--cookie|-c|--cookie-jar|-D|--dump-header|--egd-file|\
--key|--libcurl|-o|--output|--random-file|-T|--upload-file|--trace|\
--trace-ascii|--netrc-file)
_filedir
return
;;
--cacert|-E|--cert)
_filedir '@(c?(e)rt|cer|pem|der)'
return
;;
--capath)
_filedir -d
return
;;
--cert-type|--key-type)
COMPREPLY=( $( compgen -W 'DER PEM ENG' -- "$cur" ) )
return
;;
--crlfile)
_filedir crl
return
;;
-d|--data|--data-ascii|--data-binary|--data-urlencode)
if [[ $cur == \@* ]]; then
cur=${cur:1}
_filedir
COMPREPLY=( "${COMPREPLY[@]/#/@}" )
fi
return
;;
--delegation)
COMPREPLY=( $( compgen -W 'none policy always' -- "$cur" ) )
return
;;
--engine)
COMPREPLY=( $( compgen -W 'list' -- "$cur" ) )
return
;;
--ftp-method)
COMPREPLY=( $( compgen -W 'multicwd nocwd singlecwd' -- "$cur" ) )
return
;;
--ftp-ssl-ccc-mode)
COMPREPLY=( $( compgen -W 'active passive' -- "$cur" ) )
return
;;
--interface)
_available_interfaces -a
return
;;
-x|--proxy|--socks4|--socks4a|--socks5|--socks5-hostname)
_known_hosts_real
return
;;
--pubkey)
_filedir pub
return
;;
--stderr)
COMPREPLY=( $( compgen -W '-' -- "$cur" ) )
_filedir
return
;;
--tlsauthtype)
COMPREPLY=( $( compgen -W 'SRP' -- "$cur" ) )
return
;;
--host)
COMPREPLY=( $( compgen -W 'http:// https://' -- "$cur" ) )
return
;;
-ct|--content-type|-ac|--accept)
COMPREPLY=( $( compgen -W '${!mime_type_abbreviations[*]}' -- "$cur" ) )
return
;;
esac
fi
#
# Complete the server address based on ~/.ssh/known_hosts
# and ~/.ssh/config
#
# \todo Fix - cur matches only '//' when $prev is ':'
#
if [[ "$cur" == "http://" || "$cur" == "https://" ]]; then
COMPREPLY=()
local comp_ssh_hosts=`cat ~/.ssh/known_hosts | \
cut -f 1 -d ' ' | \
sed -e s/,.*//g | \
grep -v ^# | \
uniq | \
grep -v "\[" ;
cat ~/.ssh/config | \
grep "^Host " | \
awk '{print $2}'`
COMPREPLY=( $(compgen -W "${comp_ssh_hosts}" -- $cur))
return
fi
#
# Complete the petstore-cli and cURL's arguments
#
if [[ $cur == -* ]]; then
COMPREPLY=( $( compgen -W '$(_parse_help curl) $(_parse_help $1)' -- "$cur" ) )
return
fi
#
# If the argument starts with a letter this could be either an operation
# or an operation parameter
# When $cur is empty, suggest the list of operations by default
#
if [[ $cur =~ ^[A-Za-z_0-9]* ]]; then
# If operation has not been yet selected, suggest the list of operations
# otherwise suggest arguments of this operation as declared in the
# Swagger specification
if [[ -z $operation ]]; then
COMPREPLY=( $(compgen -W '${!operations[*]}' -- ${cur}) )
else
COMPREPLY=( $(compgen -W '${operation_parameters[$operation]}' -- ${cur}) )
fi
return
fi
} &&
complete -F _petstore-cli petstore-cli
# ex: ts=4 sw=4 et filetype=sh

View File

@@ -0,0 +1,47 @@
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>io.swagger</groupId>
<artifactId>BashPetstoreClientTests</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<name>Bash Swagger Petstore Client</name>
<build>
<plugins>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<executions>
<execution>
<id>bats-test</id>
<phase>integration-test</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>bats</executable>
<arguments>
<argument>--tap</argument>
<argument>tests/petstore_test.sh</argument>
</arguments>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,102 @@
#!/usr/bin/env bats
export PETSTORE_CLI="petstore-cli"
export PETSTORE_HOST="http://petstore.swagger.io"
#
# Tests for parameter handling and validation
#
@test "addPet without host" {
unset PETSTORE_HOST
run bash $PETSTORE_CLI -ac xml -ct json \
addPet id:=123321 name==lucky status==available
[[ "$output" =~ "Error: No hostname provided!!!" ]]
}
@test "addPet without content type" {
run bash $PETSTORE_CLI -ac xml --host $PETSTORE_HOST \
addPet id:=123321 name==lucky status==available
[[ "$output" =~ "Error: Request's content-type not specified!" ]]
}
@test "fakeOperation invalid operation name" {
run bash \
-c "bash $PETSTORE_CLI --host http://petstore.swagger.io fakeOperation"
[[ "$output" =~ "Error: No operation specified!" ]]
}
@test "findPetsByStatus basic auth" {
run bash \
-c "bash $PETSTORE_CLI -u alice:secret --host http://petstore.swagger.io findPetsByStatus status=s1 --dry-run"
[[ "$output" =~ "-u alice:secret" ]]
}
@test "findPetsByStatus api key" {
run bash \
-c "bash $PETSTORE_CLI --host http://petstore.swagger.io findPetsByStatus status=s1 api_key:1234 --dry-run"
[[ "$output" =~ "-H \"api_key: 1234\"" ]]
}
@test "findPetsByStatus empty api key" {
run bash \
-c "bash $PETSTORE_CLI --host http://petstore.swagger.io findPetsByStatus status=s1 --dry-run"
[[ ! "$output" =~ "-H \"api_key:" ]]
}
@test "findPetsByStatus too few values" {
run bash \
-c "bash $PETSTORE_CLI --host http://petstore.swagger.io findPetsByStatus"
[[ "$output" =~ "Error: Too few values" ]]
}
@test "findPetsByTags too few values" {
run bash \
-c "bash $PETSTORE_CLI --host http://petstore.swagger.io findPetsByTags"
[[ "$output" =~ "Error: Too few values" ]]
}
@test "findPetsByStatus status with space" {
run bash \
-c "bash $PETSTORE_CLI --host http://petstore.swagger.io findPetsByStatus \
status=available status=\"gone test\" --dry-run"
[[ "$output" =~ "status=available,gone%20test" ]]
}
@test "findPetsByStatus collection csv" {
run bash \
-c "bash $PETSTORE_CLI --host http://petstore.swagger.io findPetsByTags \
tags=TAG1 tags=TAG2 --dry-run"
[[ "$output" =~ "tags=TAG1,TAG2" ]]
}
@test "findPetsByStatus collection csv with space and question mark" {
run bash \
-c "bash $PETSTORE_CLI --host http://petstore.swagger.io findPetsByTags \
tags=TAG1 tags=\"TAG2 TEST\" tags=TAG3?TEST --dry-run"
[[ "$output" =~ "tags=TAG1,TAG2%20TEST,TAG3%3FTEST" ]]
}
#
# Operations calling the service and checking result
#
@test "addPet from parameters" {
run bash $PETSTORE_CLI -ct json -ac xml \
addPet id:=123321 name==lucky status==available
[[ "$output" =~ "<id>123321</id>" ]]
}
@test "addPet from pipe" {
run bash \
-c "echo '{\"id\": 37567, \"name\": \"lucky\", \"status\": \"available\"}' | \
bash $PETSTORE_CLI -ct json -ac xml addPet -"
[[ "$output" =~ "<id>37567</id>" ]]
}