Skip to content

Commit

Permalink
Add test function for the announcement checker class
Browse files Browse the repository at this point in the history
  • Loading branch information
shrivaths16 committed Oct 16, 2023
1 parent f8fb1f1 commit d9947c3
Show file tree
Hide file tree
Showing 4 changed files with 77 additions and 26 deletions.
36 changes: 19 additions & 17 deletions docs/make_bulletin_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,37 +2,39 @@
import os

# Set the file paths
input_md_file = os.path.join(os.path.dirname(__file__), 'bulletin.md')
output_json_file = os.path.join(os.path.dirname(__file__), 'bulletin.json')
input_md_file = os.path.join(os.path.dirname(__file__), "bulletin.md")
output_json_file = os.path.join(os.path.dirname(__file__), "bulletin.json")


def generate_json_file():
with open(input_md_file, 'r', encoding='utf-8') as md_file:
with open(input_md_file, "r", encoding="utf-8") as md_file:
markdown_content = md_file.read()
bulletin_json = []
content = ''
content = ""

# Initialize title and date with default values
title = "DEFAULT_TITLE"
date = "DEFAULT_DATE"

for line in markdown_content.split('\n'):
if line.startswith('---'):
bulletin_json.append({'title': title, 'date': date, 'content':content})
content = ''
for line in markdown_content.split("\n"):
if line.startswith("---"):
bulletin_json.append({"title": title, "date": date, "content": content})
content = ""
# Reset title and date to their default values after each section
title = "DEFAULT_TITLE"
date = "DEFAULT_DATE"
elif line.startswith('##'):
elif line.startswith("##"):
title = line[3:].strip()
elif line.startswith('_'):
date = line[1:len(line)-1].strip()
elif line.startswith("_"):
date = line[1 : len(line) - 1].strip()
else:
content += (line + '\n')
# Append last section
bulletin_json.append({'title': title, 'date': date, 'content':content})
with open(output_json_file, 'w', encoding='utf-8') as json_file:
content += line + "\n"
# Append last section
bulletin_json.append({"title": title, "date": date, "content": content})

with open(output_json_file, "w", encoding="utf-8") as json_file:
json.dump(bulletin_json, json_file, ensure_ascii=False, indent=4)

if __name__ == '__main__':

if __name__ == "__main__":
generate_json_file()
4 changes: 1 addition & 3 deletions sleap/gui/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,9 +170,7 @@ def __init__(
self.state.connect("show non-visible nodes", self.plotFrame)

self.release_checker = ReleaseChecker()
self.announcement_checker = AnnouncementChecker(
app = self
)
self.announcement_checker = AnnouncementChecker(app=self)

if self.state["share usage data"]:
ping_analytics()
Expand Down
20 changes: 15 additions & 5 deletions sleap/gui/web.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@

REPO_ID = "talmolab/sleap"
ANALYTICS_ENDPOINT = "https://analytics.sleap.ai/ping"
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
BASE_DIR = os.path.dirname(
os.path.abspath(os.path.join(__file__, os.path.pardir, os.pardir))
)
BULLETIN_JSON = os.path.join(BASE_DIR, "..", "docs", "bulletin.json")


Expand Down Expand Up @@ -156,13 +158,18 @@ class AnnouncementChecker:

app: "MainWindow"
bulletin_json_path: str = BULLETIN_JSON
previous_announcement_date: str = None
_previous_announcement_date: str = None
_latest_data: Optional[Dict[str, str]] = None

@property
def previous_announcement_date(self):
_previous_announcement_date = self.app.state["announcement last seen date"]
return _previous_announcement_date

def _read_bulletin_data(self) -> Dict[str, str]:
"""Reads the bulletin data from the JSON file."""
try:
with open(self.bulletin_json_path, 'r', encoding='utf-8') as jsf:
with open(self.bulletin_json_path, "r") as jsf:
data = json.load(jsf)
return data[0]
except FileNotFoundError:
Expand All @@ -171,8 +178,11 @@ def _read_bulletin_data(self) -> Dict[str, str]:
def get_latest_announcement(self) -> Optional[Tuple[str, str]]:
"""Return latest announcements on the releases page not seen by user."""
self._latest_data = self._read_bulletin_data()
if self._latest_data and self._latest_data['date'] != self.previous_announcement_date:
return (self._latest_data['date'], self._latest_data['content'])
if (
self._latest_data
and self._latest_data["date"] != self.previous_announcement_date
):
return (self._latest_data["date"], self._latest_data["content"])
return None

def update_announcement(self):
Expand Down
43 changes: 42 additions & 1 deletion tests/gui/test_web.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
import pandas as pd
from sleap.gui.web import ReleaseChecker, Release, get_analytics_data, ping_analytics
from sleap.gui.web import (
ReleaseChecker,
Release,
AnnouncementChecker,
get_analytics_data,
ping_analytics,
)
import pytest
from sleap.gui.app import create_app
import json
import os


def test_release_from_json():
Expand Down Expand Up @@ -72,6 +81,38 @@ def test_release_checker():
assert checker.releases[1] != rls_test


def test_announcementchecker():

BULLETIN_JSON_PATH = os.environ["test_bulletin_json"]
app = create_app()
app.state = {}
app.state["announcement last seen date"] = "10/10/2023"
checker = AnnouncementChecker(app=app, bulletin_json_path=BULLETIN_JSON_PATH)

# Check if the announcement checker gets the correct date from the app
assert checker.previous_announcement_date == "10/10/2023"

# Create dummy JSON file to check
bulletin_data = [
{"title": "title1", "date": "10/11/2023", "content": "New announcement"},
{"title": "title2", "date": "10/07/2023", "content": "Old Announcment"},
]
with open(BULLETIN_JSON_PATH, "w") as test_file:
json.dump(bulletin_data, test_file)
assert checker._read_bulletin_data() == bulletin_data[0]

# Check if latest announcement is fetched
announcement = checker.get_latest_announcement()
assert announcement == ("10/11/2023", "New announcement")

checker.update_announcement()
assert app.state["announcement last seen date"] == "10/11/2023"
assert app.state["announcement"] == "New announcement"

# Delete the JSON file
os.remove(BULLETIN_JSON_PATH)


def test_get_analytics_data():
analytics_data = get_analytics_data()
assert "platform" in analytics_data

0 comments on commit d9947c3

Please sign in to comment.