Skip to content

Commit

Permalink
Merge pull request #1198 from ScilifelabDataCentre/cli_display_motd
Browse files Browse the repository at this point in the history
Adapt MOTD endpoint for displaying motd in cli
  • Loading branch information
i-oden authored Jun 17, 2022
2 parents 12a0f4a + feb9563 commit 80e0319
Show file tree
Hide file tree
Showing 9 changed files with 203 additions and 78 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,3 +112,7 @@ Please add a _short_ line describing the PR you make, if the PR implements a spe

- Change FontAwesome source link to own license ([#1194](https://github.com/ScilifelabDataCentre/dds_web/pull/1194))
- Display MOTD on web ([#1196](https://github.com/ScilifelabDataCentre/dds_web/pull/1196))

## Sprint (2022-06-15 - 2022-06-29)

- Get MOTD from API ([#1198](https://github.com/ScilifelabDataCentre/dds_web/pull/1198))
6 changes: 2 additions & 4 deletions dds_web/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,16 +189,14 @@ def create_app(testing=False, database_uri=None):
@app.before_request
def prepare():
"""Populate flask globals for template rendering"""
from dds_web.utils import validate_major_cli_version
from dds_web.utils import validate_major_cli_version, get_latest_motd
from dds_web.errors import VersionMismatchError

if "/api/v1" in flask.request.path:
validate_major_cli_version()

# Get message of the day
flask.g.motd = (
db.session.query(models.MOTD).order_by(models.MOTD.date_created.desc()).first()
)
flask.g.motd = get_latest_motd()

flask.g.current_user = None
flask.g.current_user_emails = None
Expand Down
2 changes: 1 addition & 1 deletion dds_web/api/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ def output_json(data, code, headers=None):
# Super Admins ###################################################################### Super Admins #

api.add_resource(superadmin_only.AllUnits, "/unit/info/all", endpoint="all_units")
api.add_resource(superadmin_only.MOTD, "/unit/motd", endpoint="motd")
api.add_resource(superadmin_only.MOTD, "/motd", endpoint="motd")

# Invoicing ############################################################################ Invoicing #
api.add_resource(user.ShowUsage, "/usage", endpoint="usage")
7 changes: 7 additions & 0 deletions dds_web/api/superadmin_only.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import flask_restful
import flask
import structlog
import sqlalchemy

# Own modules
from dds_web import auth, db
Expand Down Expand Up @@ -86,3 +87,9 @@ def post(self):
db.session.commit()

return {"message": "The MOTD was successfully added to the database."}

@handle_db_error
def get(self):
"""Get the latest MOTD from database."""
motd = utils.get_latest_motd()
return {"message": motd}
9 changes: 9 additions & 0 deletions dds_web/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -486,3 +486,12 @@ def validate_major_cli_version() -> None:
raise VersionMismatchError(
message=f"You have an outdated version of the DDS CLI installed. Please upgrade to version {latest_version} and try again."
)


#


def get_latest_motd():
"""Return latest MOTD."""
motd_object = models.MOTD.query.order_by(models.MOTD.date_created.desc()).first()
return motd_object.message if motd_object else ""
3 changes: 2 additions & 1 deletion tests/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,8 @@ class DDSEndpoint:
USAGE = BASE_ENDPOINT + "/usage"
INVOICE = BASE_ENDPOINT + "/invoice"

# Units
# Superadmins only
LIST_UNITS_ALL = BASE_ENDPOINT + "/unit/info/all"
MOTD = BASE_ENDPOINT + "/motd"

TIMEOUT = 5
160 changes: 160 additions & 0 deletions tests/test_superadmin_only.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
# IMPORTS ################################################################################ IMPORTS #

# Standard library
import http
from urllib import response
import time

# Own
from dds_web import db
from dds_web.api import user
from dds_web.database import models
import tests

# CONFIG ################################################################################## CONFIG #

users = {
"Researcher": "researchuser",
"Unit Personnel": "unituser",
"Unit Admin": "unitadmin",
"Super Admin": "superadmin",
}

# TESTS #################################################################################### TESTS #


def get_token(username, client):
return tests.UserAuth(tests.USER_CREDENTIALS[username]).token(client)


# AllUnits


def test_list_units_as_not_superadmin(client):
"""Only Super Admin can list users."""
no_access_users = users.copy()
no_access_users.pop("Super Admin")

for u in no_access_users:
token = get_token(username=users[u], client=client)
response = client.get(tests.DDSEndpoint.LIST_UNITS_ALL, headers=token)
assert response.status_code == http.HTTPStatus.FORBIDDEN


def test_list_units_as_super_admin(client):
"""List units as Super Admin."""
all_units = models.Unit.query.all()

token = get_token(username=users["Super Admin"], client=client)
response = client.get(tests.DDSEndpoint.LIST_UNITS_ALL, headers=token)
assert response.status_code == http.HTTPStatus.OK

keys = response.json.get("keys")
units = response.json.get("units")
assert keys and units

assert keys == [
"Name",
"Public ID",
"External Display Name",
"Days In Available",
"Days In Expired",
"Safespring Endpoint",
"Contact Email",
]
assert len(all_units) == len(units)

for unit in all_units:
expected = {
"Name": unit.name,
"Public ID": unit.public_id,
"External Display Name": unit.external_display_name,
"Contact Email": unit.contact_email,
"Safespring Endpoint": unit.safespring_endpoint,
"Days In Available": unit.days_in_available,
"Days In Expired": unit.days_in_expired,
}
assert expected in units


# MOTD


def test_create_motd_not_superadmin(client):
"""Create a new message of the day, using everything but Super Admin access."""
no_access_users = users.copy()
no_access_users.pop("Super Admin")

for u in no_access_users:
token = get_token(username=users[u], client=client)
response = client.post(tests.DDSEndpoint.MOTD, headers=token)
assert response.status_code == http.HTTPStatus.FORBIDDEN


def test_create_motd_as_superadmin_no_json(client):
"""Create a new message of the day, using a Super Admin account, but without any json."""
token = get_token(username=users["Super Admin"], client=client)
response = client.post(tests.DDSEndpoint.MOTD, headers=token)
assert response.status_code == http.HTTPStatus.BAD_REQUEST
assert "Required data missing from request!" in response.json.get("message")


def test_create_motd_as_superadmin_no_message(client):
"""Create a new message of the day, using a Super Admin account, but without any message."""
token = get_token(username=users["Super Admin"], client=client)
response = client.post(tests.DDSEndpoint.MOTD, headers=token, json={"test": "test"})
assert response.status_code == http.HTTPStatus.BAD_REQUEST
assert "No MOTD specified." in response.json.get("message")


def test_create_motd_as_superadmin_empty_message(client):
"""Create a new message of the day, using a Super Admin account, but with empty message."""
token = get_token(username=users["Super Admin"], client=client)
response = client.post(tests.DDSEndpoint.MOTD, headers=token, json={"message": ""})
assert response.status_code == http.HTTPStatus.BAD_REQUEST
assert "No MOTD specified." in response.json.get("message")


def test_create_motd_as_superadmin_success(client):
"""Create a new message of the day, using a Super Admin account."""
token = get_token(username=users["Super Admin"], client=client)
response = client.post(tests.DDSEndpoint.MOTD, headers=token, json={"message": "test"})
assert response.status_code == http.HTTPStatus.OK
assert "The MOTD was successfully added to the database." in response.json.get("message")

assert models.MOTD.query.filter_by(message="test")


def test_get_motd_no_message(client):
"""Get latest MOTD from database."""
response = client.get(tests.DDSEndpoint.MOTD, headers={"X-CLI-Version": "0.0.0"})
assert response.status_code == http.HTTPStatus.OK
assert not response.json.get("message")


def test_get_motd(client):
"""Get latest MOTD from database."""
# Create first message
token = get_token(username=users["Super Admin"], client=client)
response = client.post(tests.DDSEndpoint.MOTD, headers=token, json={"message": "test"})
assert response.status_code == http.HTTPStatus.OK
assert models.MOTD.query.filter_by(message="test")

# Get first message
response1 = client.get(tests.DDSEndpoint.MOTD, headers={"X-CLI-Version": "0.0.0"})
assert response1.status_code == http.HTTPStatus.OK
assert "test" in response1.json.get("message")

time.sleep(5)

# Create new message
response2 = client.post(
tests.DDSEndpoint.MOTD, headers=token, json={"message": "something else"}
)
assert response2.status_code == http.HTTPStatus.OK
assert models.MOTD.query.filter_by(message="something else")

# Check that new message is displayed
response3 = client.get(tests.DDSEndpoint.MOTD, headers={"X-CLI-Version": "0.0.0"})
assert response3.status_code == http.HTTPStatus.OK
assert "something else" in response3.json.get("message")
72 changes: 0 additions & 72 deletions tests/test_unit_list.py

This file was deleted.

18 changes: 18 additions & 0 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -892,3 +892,21 @@ def test_validate_major_cli_version_jsonerror(client: FlaskClient, disable_reque
utils.validate_major_cli_version()
assert pypi_response.call_count == 1
assert "Failed checking latest DDS PyPi version." in str(err.value)


# get_latest_motd


def test_get_latest_motd_no_motd(client: FlaskClient):
motd = utils.get_latest_motd()
assert not motd


def test_get_latest_motd(client: FlaskClient):
new_message: str = "test message"
new_motd = models.MOTD(message=new_message, date_created=utils.current_time())
db.session.add(new_motd)
db.session.commit()

motd = utils.get_latest_motd()
assert motd == new_message

0 comments on commit 80e0319

Please sign in to comment.