"""This script uploads a cucumber test result file to JIRA"""
import argparse
import base64
import getpass
import os
import sys
from pathlib import Path
import requests
from requests.auth import HTTPBasicAuth
from ska_ser_skallop.xray.upload_multipart import upload_multipart
if not (XRAY_UPLOAD_URL := os.getenv("XRAY_UPLOAD_URL")):
XRAY_UPLOAD_URL = (
"https://jira.skatelescope.org/rest/raven/1.0/import/execution/cucumber"
)
[docs]def handle_multipart_upload(args):
if not (host := os.getenv("JIRA_URL")):
host = "https://jira.skatelescope.org"
if not (token := os.getenv("JIRA_AUTH")):
assert (
args.username and args.password
), "expected a username and password since no JIRA_AUTH has been set"
token = base64.b64encode(
f"{args.username}:{args.password}".encode("ascii")
).decode("ascii")
results_file = Path(args.cucumber_file.name)
test_exec_desc_file = Path(args.info.name)
result = upload_multipart(host, token, results_file, test_exec_desc_file)
if args.verbose:
if result:
print(
f'test results uploaded to {result["key"]}: {host}/browse/{result["key"]}'
)
[docs]def upload_results_file(args: argparse.Namespace) -> str:
"""POST the cucumber JSON results file to JIRA
:param args: The passed parameters
:return: The JSON response from the server
:raises SystemExit: Upon request failure
"""
if args.verbose:
print(
f"\nUploading cucumber file {args.cucumber_file.name} to {XRAY_UPLOAD_URL}"
)
headers = {
"Content-type": "application/json",
"Accept": "application/json",
}
with open(args.cucumber_file.name, "rb") as open_file:
if args.username:
if args.verbose:
print("\nUsing username & password credentials")
response = requests.post(
XRAY_UPLOAD_URL,
auth=HTTPBasicAuth(args.username, args.password),
data=open_file,
headers=headers,
)
else:
headers["Authorization"] = f"Basic {args.jira_auth_token}"
if args.verbose:
print("\nUsing JIRA_AUTH environment variable as credentials")
response = requests.post(XRAY_UPLOAD_URL, data=open_file, headers=headers)
try:
response.raise_for_status()
except requests.exceptions.HTTPError as err:
if response.status_code == 400:
raise SystemExit("No execution results where provided.") from err
if response.status_code == 401:
raise SystemExit(
"Authentication failure, either the credentials are incorrect or "
"the Xray license has expired."
) from err
if response.status_code == 500:
raise SystemExit(
"An internal error occurred when importing execution results."
) from err
raise SystemExit(err) from err
if args.verbose:
print(f"Result: {response.json()}")
return response.json()
[docs]def temp():
x = open("", "r")
return x
[docs]def main():
"""Script entrypoint"""
parser = argparse.ArgumentParser(
description=(
"Uploads a cucumber results file to JIRA by way of the XRAY extension. "
"Either use username/password or set the environment variable JIRA_AUTH "
"for authentication."
)
)
parser.add_argument(
"-f",
"--cucumber-file",
type=argparse.FileType("r"),
required=True,
help="Path to the cucumber JSON results file.",
)
parser.add_argument(
"-u", "--username", type=str, default="", help="JIRA account username"
)
parser.add_argument(
"-p",
"--password",
type=str,
default="",
help=(
"Password for the JIRA user. If not specified and the environment variable "
"`JIRA_AUTH` is not set then you will be prompted for one."
),
)
parser.add_argument(
"-v",
"--verbose",
required=False,
action="store_true",
help="Verbose output",
)
parser.add_argument(
"-i",
"--info",
type=argparse.FileType("r"),
required=False,
help="Path to test execution description json file (as defined by user)",
)
args = parser.parse_args()
setattr(args, "jira_auth_token", os.environ.get("JIRA_AUTH", None))
if not args.jira_auth_token:
if not args.username:
print(
"A username is required when the environment variable JIRA_AUTH is not "
"set"
)
sys.exit(0)
if not args.password:
stdin_password = getpass.getpass()
setattr(args, "password", stdin_password)
if args.info:
handle_multipart_upload(args)
else:
upload_results_file(args)
if __name__ == "__main__":
main()