Skip to content

Commit

Permalink
✨ Add tests
Browse files Browse the repository at this point in the history
  • Loading branch information
kinegratii committed Jan 23, 2024
1 parent a12a0c2 commit a6fd5eb
Show file tree
Hide file tree
Showing 5 changed files with 44 additions and 15 deletions.
7 changes: 4 additions & 3 deletions borax/calendars/festivals2.py
Original file line number Diff line number Diff line change
Expand Up @@ -982,7 +982,7 @@ def get_code_set(self) -> Set[str]:
"""
return set([f.encode() for f in self.data])

def extend_unique(self, other):
def extend_unique(self, other: Union[collections.UserList, List[str], 'FestivalLibrary']) -> 'FestivalLibrary':
"""Add a new festival if code does not exist.
"""
f_codes = {f.encode() for f in self.data}
Expand Down Expand Up @@ -1117,7 +1117,8 @@ def list_days(self, start_date=None, end_date=None):
return data_items

def iter_month_daytuples(self, year: int, month: int, firstweekday: int = 0, return_pos: bool = False):
"""迭代返回公历月份(含前后完整日期)中每个日期信息
"""return all day info for a whole solar month as (day_integer, day_text, wrapped_date)
The day_text show in the order:festival_name,term_name, lunar_day_text
"""
row = 0
cal = calendar.Calendar(firstweekday=firstweekday)
Expand Down Expand Up @@ -1157,7 +1158,7 @@ def to_csv(self, path_or_buf):
fileobj = path_or_buf.open('w', encoding='utf8', newline='')
else:
fileobj = path_or_buf
writer = csv.writer(fileobj, )
writer = csv.writer(fileobj)
for festival in self:
row = (festival.encode(), festival.name, festival.catalog)
writer.writerow(row)
Expand Down
4 changes: 2 additions & 2 deletions borax/calendars/ui.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,8 @@ def __init__(self, master=None, firstweekday: int = 0, year: int = 0, month: int
else:
self._library = festival_source
self._v_day_matrix = [[tk.StringVar() for _ in range(7)] for _ in range(6)]
self._d_selected_date = None # type: Optional[WrappedDate]
self._callbacks = {} # type: Dict[str,Callable]
self._d_selected_date: Optional[WrappedDate] = None
self._callbacks: Dict[str, Callable] = {}
self._day_cell_indexes = -1, -1 # The cell indexes of first and last day in this month.

self._cal_obj = calendar.Calendar(firstweekday=self._firstweekday)
Expand Down
28 changes: 18 additions & 10 deletions borax/capp/borax_calendar_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,9 @@

from borax import __version__ as borax_version
from borax.calendars.festivals2 import FestivalLibrary, WrappedDate
from borax.calendars.lunardate import TextUtils, TERMS_CN
from borax.calendars.lunardate import TextUtils, TERMS_CN, TERM_PINYIN
from borax.calendars.ui import CalendarFrame, FestivalTableFrame
from borax.calendars.utils import ThreeNineUtils
from borax.capp.festival_creator import FestivalCreatePanel

library = FestivalLibrary.load_builtin().sort_by_countdown()
Expand All @@ -27,6 +28,9 @@


class WDateVar(tk.StringVar):
"""A tkinter variable for WrappedDate object.
Use set_date/get_date instead of set/get function.
"""

def __init__(self, master=None, value=None, name=None, date_fmt='%Y-%m-%d'):
super().__init__(master, value, name)
Expand Down Expand Up @@ -176,7 +180,11 @@ def set_selected_date(self, wd: WrappedDate = None):
week_cn = ld.cn_week
self.label_widgets['solar_week'].config(text=f'星期{week_cn}')
self.label_widgets['solar_gz'].config(text=ld.gz_str())
self.label_widgets['festival'].config(text=' '.join(library.get_festival_names(sd)))
day_labels = library.get_festival_names(sd)
three_night_label = ThreeNineUtils.get_39label(sd)
if three_night_label:
day_labels.append(three_night_label)
self.label_widgets['festival'].config(text=' '.join(day_labels))


class GanzhiPanel(ttk.Frame):
Expand All @@ -194,7 +202,7 @@ def __init__(self, master=None, **kwargs):

self.year_list = ttk.Treeview(self, column=("年份",), show='headings', height=5)
self.year_list.column("# 1", anchor=tk.CENTER)
self.year_list.heading("# 1", text="年份")
self.year_list.heading("# 1", text="农历年份")
self.year_list.pack(side='left', expand=True, fill=tk.BOTH)

def _show_years(self, gz_offset: int):
Expand All @@ -212,7 +220,7 @@ class TermPanel(ttk.Frame):
def __init__(self, master=None, **kwargs):
super().__init__(master, **kwargs)

columns = ("序号", "节气", "太阳地心视黄经(度)")
columns = ("序号", "节气", "识别码(拼音首字母)", "太阳地心视黄经(度)")
self.term_table = ttk.Treeview(self, column=columns, show='headings', height=5)
self.term_table.pack(side='top', expand=True, fill=tk.BOTH)
for i, name in enumerate(columns, start=1):
Expand All @@ -221,7 +229,7 @@ def __init__(self, master=None, **kwargs):

for tindex, tname in enumerate(TERMS_CN): # 1-285
dg = (285 + 15 * tindex) % 360
self.term_table.insert('', 'end', text="1", values=(tindex + 1, tname, dg))
self.term_table.insert('', 'end', text="1", values=(tindex, tname, TERM_PINYIN[tindex], dg))


class CApp(ttk.Frame):
Expand All @@ -238,8 +246,8 @@ def __init__(self, master=None):
self.cal_panel.bind_date_selected(self.on_show_date_detail)

ttk.Separator(self, orient=tk.VERTICAL).pack(side='left', fill=tk.Y, expand=True)
self._table_festival_libray = library
columns = (("name", 100), ("description", 180), ("code", 80), ("next_day", 150), ("countdown", 60))
self._table_festival_library = library
columns = (("name", 120), ("description", 160), ("code", 80), ("next_day", 150), ("countdown", 60))
self._cs = FestivalTableFrame(self, columns=columns, festival_source=library, countdown_ordered=True)
self._cs.pack(side='right', expand=True, fill=tk.BOTH, padx=10, pady=10)

Expand All @@ -263,7 +271,7 @@ def create_top_menu(self):
viewmenu.add_radiobutton(label=name, variable=self._style_var, command=self._change_theme)
menu_bar.add_cascade(label='界面主题', menu=viewmenu)
menu_bar.add_command(label='日期计算', command=self.start_tool_dlg)
menu_bar.add_command(label='干支节气', command=self.start_gz_dlg)
menu_bar.add_command(label='节气干支', command=self.start_gz_dlg)
menu_bar.add_command(label='创建节日', command=self.start_festival_dlg)
source_menu = tk.Menu(menu_bar)
for source in ('basic', 'ext1'):
Expand Down Expand Up @@ -305,10 +313,10 @@ def _create_gz_dialog(self):
self._gz_dlg = tk.Toplevel(self)
self._gz_dlg.resizable(False, False)
notebook = ttk.Notebook(self._gz_dlg)
d = GanzhiPanel(notebook)
notebook.add(d, text='干支')
tp = TermPanel(notebook)
notebook.add(tp, text='节气')
d = GanzhiPanel(notebook)
notebook.add(d, text='干支')
notebook.pack(side='top')
self._gz_dlg.lift()

Expand Down
13 changes: 13 additions & 0 deletions borax/ui/widgets.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,3 +55,16 @@ def reset(self):
@property
def state(self):
return self._state


class MessageLabel(tk.Label):
"""A label that can show text in a short time.Variable binding is not supported."""
_key2colors = {'error': 'red', 'warning': 'orange', 'success': 'green'}

def show_text(self, text: str, text_color: str = 'black', splash_ms: int = 0):
self.config({'text': text, 'fg': MessageLabel._key2colors.get(text_color, text_color)})
if splash_ms:
self.after(splash_ms, self._clear)

def _clear(self):
self.config({'text': ''})
7 changes: 7 additions & 0 deletions tests/test_festival_library.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,13 @@ def test_unique(self):
fl.extend_unique(['205026', '89005'])
self.assertEqual(3, len(fl))

def test_unique_for_basic_library(self):
fl = FestivalLibrary.load_builtin('basic')
total_1 = len(fl)
fl.extend_term_festivals()
total_2 = len(fl)
self.assertEqual(22, total_2 - total_1)

def test_edit(self):
fl = FestivalLibrary()
fl.load_term_festivals()
Expand Down

0 comments on commit a6fd5eb

Please sign in to comment.