Skip to content

Commit

Permalink
fix(README-+-Tests): Added schematic to readme and testing for CLI
Browse files Browse the repository at this point in the history
  • Loading branch information
tabbott36 committed Jul 15, 2024
1 parent 07fd67b commit b5ad815
Show file tree
Hide file tree
Showing 13 changed files with 158 additions and 278 deletions.
Binary file added frb-voe-workflow.pdf
Binary file not shown.
85 changes: 85 additions & 0 deletions frbvoe/backend/tns.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
"""VOEvent Server Blueprint."""

import picologging as logging
from pymongo.errors import PyMongoError
from sanic import Blueprint
from sanic.request import Request
from sanic.response import json as json_response
from sanic_ext import openapi

from frbvoe.models.tns import TNS

logging.basicConfig()
log = logging.getLogger()

tns = Blueprint("tns", url_prefix="/")


# Post at /submit_tns
@tns.post("submit_tns")
@openapi.response(201, description="Submits an FRB to the TNS.")
# Validate the TNS report, submit to the TNS, and save the TNS name to the MongoDB
async def submit_tns(
request: Request, proprierary_period: int = 10, sandbox: bool = True
):
"""Submits a TNS (Transient Name Server) report.
Args:
request (Request): The request object.
proprierary_period (int, optional): The proprietary period for the TNS report.
Defaults to 10.
sandbox (bool, optional): If true, submits the report to the TNS sandbox.
Defaults to True.
Returns:
dict: A dictionary containing the validation status,
TNS status, database status, and the inserted ID.
"""
# Validate the VOEvent
try:
log.info("Validating the TNS Report")
tns_report = TNS(**request.json)
validation_status = "Success"
status_code = 200
except Exception as validation_error:
log.exception(f"Error while validating the VOEvent: {validation_error}")
validation_status = "Failure"
status_code = 400

# Submit to the TNS
try:
log.info("Submitting the VOEvent to TNS")
tns_report.submit(proprierary_period, sandbox)
tns_status = "Success"
except Exception as tns_error:
log.exception(f" While sending the VOEvent to the TNS: {tns_error}")
tns_status = "Failure"
status_code = 500

# Save VOEvent to MongoDB
# DB Name: frbvoe, Collection: tns, Document: TNS Name Dict
try:
log.info("Saving the TNS name to MongoDB")
mongo = request.app.ctx.mongo
insert_result = await mongo["frbvoe"]["tns"].insert_one(tns_report.model_dump())
database_status = "Success"
except (Exception, PyMongoError) as mongo_error:
log.exception(f" While saving the TNS name to MongoDB: {mongo_error}")
database_status = "Failure"
status_code = 500

print(
f"""Validation: {validation_status}\n
TNS: {tns_status}\n
Database : {database_status}"""
)

return json_response(
{
"validation": validation_status,
"tns": tns_status,
"database": database_status,
"id": insert_result.inserted_id,
},
status=status_code,
)
13 changes: 8 additions & 5 deletions frbvoe/cli/tns.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

import click

from frbvoe.backend.tns import TNS


@click.group(name="tns", help="TNS Tools.")
def tns():
Expand All @@ -10,13 +12,14 @@ def tns():


@tns.command("submit", help="Submit an FRB to the TNS.")
@click.option("--username", help="TNS username.")
@click.option(
"--period", default=2, help="Proprietary period of the FRB.", show_default=True
"--period", default=10, help="Proprietary period of the FRB.", show_default=True
)
@click.option(
"--sandbox", help="Set to False when submitting to the live TNS.", show_default=True
"--sandbox",
help="Submit to the sandbox TNS (if True) or live TNS (if False).",
show_default=True,
)
def send(username, period, sandbox):
def submit(proprietary_period, sandbox):
"""Submit an FRB to the TNS."""
click.echo(f"submit FRB to TNS. {username} {period} {sandbox}")
TNS.submit(proprietary_period, sandbox)
30 changes: 0 additions & 30 deletions frbvoe/utilities/tns.py

This file was deleted.

File renamed without changes.
42 changes: 42 additions & 0 deletions tests/test_backend/test_voe.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import pytest

from frbvoe.models.voe import VOEvent


def test_voevent_creation():
# Test valid VOEvent creation
voevent = VOEvent(
kind="detection",
observatory_name="CHIME",
date="2020-01-13 16:55:08.844845",
email="[email protected]",
right_ascension=55.2938,
declination=14.2049,
pos_error_deg_95=0.001,
importance=0.9979,
)
assert voevent.kind == "detection"
assert voevent.observatory_name == "CHIME"
assert voevent.date == "2020-01-13 16:55:08.844845"
assert voevent.email == "[email protected]"
assert voevent.right_ascension == 55.2938
assert voevent.declination == 14.2049
assert voevent.pos_error_deg_95 == 0.001
assert voevent.importance == 0.9979

# Test invalid VOEvent creation with missing required fields
with pytest.raises(ValueError):
voevent = VOEvent(kind="detection", observatory_name="CHIME")

# Test invalid VOEvent creation with invalid field values
with pytest.raises(ValueError):
voevent = VOEvent(
kind="invalid_kind",
observatory_name="CHIME",
date="2020-01-13 16:55:08.844845",
email="invalid_email",
right_ascension=55.2938,
declination=14.2049,
pos_error_deg_95=0.001,
importance=0.9979,
)
1 change: 1 addition & 0 deletions tests/test_cli/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""Fast Radio Burst Virtual Observatory Event (FRB-VOE)."""
1 change: 0 additions & 1 deletion tests/test_cli/test_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,3 @@ def test_version_command():
runner = CliRunner()
result = runner.invoke(cli, ["version"])
assert result.exit_code == 0
assert "FRB VOE version" in result.output
10 changes: 10 additions & 0 deletions tests/test_cli/test_tns.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
from click.testing import CliRunner

from frbvoe.cli.tns import submit


def test_tns_submit():
runner = CliRunner()
result = runner.invoke(submit, ["--help"])
assert result.exit_code == 0
assert "Usage: submit [OPTIONS]" in result.output
63 changes: 12 additions & 51 deletions tests/test_cli/test_voe.py
Original file line number Diff line number Diff line change
@@ -1,56 +1,17 @@
from datetime import datetime
from click.testing import CliRunner

from frbvoe.models.voe import VOEvent
from frbvoe.cli.voe import send, voe


def test_voevent():
# Create a valid VOEvent object
voevent = VOEvent(
kind="detection",
observatory_name="CHIME",
date="2020-01-13 16:55:08.844845",
email="[email protected]",
right_ascension=55.2938,
declination=14.2049,
pos_error_deg_95=0.001,
importance=0.9979,
)
def test_voe():
runner = CliRunner()
result = runner.invoke(voe, ["--help"])
assert result.exit_code == 0
assert "Usage: voe [OPTIONS]" in result.output

# Check that the object is valid
assert voevent.is_valid()

# Check that the attributes are set correctly
assert voevent.kind == "detection"
assert voevent.observatory_name == "CHIME"
assert voevent.date == datetime.strptime(
"2020-01-13 16:55:08.844845", "%Y-%m-%d %H:%M:%S.%f"
)
assert voevent.email == "[email protected]"
assert voevent.right_ascension == 55.2938
assert voevent.declination == 14.2049
assert voevent.pos_error_deg_95 == 0.001
assert voevent.importance == 0.9979

# Check that optional attributes are set to None by default
assert voevent.semi_major is None
assert voevent.semi_minor is None
assert voevent.sampling_time is None
assert voevent.bandwidth is None
assert voevent.central_frequency is None
assert voevent.npol is None
assert voevent.bits_per_sample is None
assert voevent.gain is None
assert voevent.tsys is None
assert voevent.internal_id is None
assert voevent.dm is None
assert voevent.dm_error is None
assert voevent.width is None
assert voevent.snr is None
assert voevent.flux is None
assert voevent.website is None
assert voevent.tns_name is None
assert voevent.update_message is None

# Check that tokenized attributes are set to None by default
assert voevent.comet_port == 8098
assert voevent.email_password is None
def test_send():
runner = CliRunner()
result = runner.invoke(send, ["--help"])
assert result.exit_code == 0
assert "Usage: send [OPTIONS]" in result.output
95 changes: 0 additions & 95 deletions tests/test_utilities/test_TNSAgent.py

This file was deleted.

Loading

0 comments on commit b5ad815

Please sign in to comment.