Files
breeze/tests/apps_behavior.zi
T

1161 lines
56 KiB
Ziran

#import, file "lumi_apps_behavior.zi";
#import, file "habits_shop_apps_behavior.zi";
#import, file "habits_list_apps_behavior.zi";
#import, file "habits_stats_apps_behavior.zi";
#import, file "practice_home_apps_behavior.zi";
#import, file "practice_manual_apps_behavior.zi";
#import, file "practice_settings_apps_behavior.zi";
#import, file "practice_results_apps_behavior.zi";
#import, file "practice_sessions_apps_behavior.zi";
#import, file "apps_locale_behavior.zi";
#import, file "node_reload_apps_behavior.zi";
Packages :: #import, file "../src/apps/package_manager.zi";
#import, file "../src/apps/package_release.zi";
#import, file "../src/apps/node_apps.zi";
#import, file "../src/apps/catalog.zi";
#import, file "../src/apps/module_host.zi";
#import, file "../src/apps/asset_paths.zi";
#import, file "../src/apps/module_types.zi";
c_cache :: #system_library "c";
ModuleTestUseCache :: (enabled: bool) #foreign c_cache;
ModuleTestCachedReads :: (index: s32) -> s32 #foreign c_cache;
ModuleTestBundleOpens :: () -> s32 #foreign c_cache;
ModuleTestInstanceOpens :: () -> s32 #foreign c_cache;
ModuleTestCorruptCachedLists :: (enabled: bool) #foreign c_cache;
ModuleTestFailInstantiate :: () #foreign c_cache;
ModuleTestFailRun :: () #foreign c_cache;
ModuleTestSetRevision :: (index: s32, revision: s32) #foreign c_cache;
ModuleTestYield :: () #foreign c_cache;
ModuleTestBlockParser :: (enabled: bool) #foreign c_cache;
ModuleTestParserStarted :: () -> bool #foreign c_cache;
ModuleTestNow :: () -> float64 #foreign c_cache;
ModuleTestPrepare :: (index: s32, bytes: string) -> s32 {
result: s32 = 0
for attempt: 0..20000 {
result = AppsPreparePackage(index, bytes)
if result != 0 {
return result
}
ModuleTestYield()
}
return result
}
// Download validation owns its parser until cancellation finishes. Polling a
// held parser must leave the visible app usable and return within a frame.
CheckNodePackagePreparation :: (bytes: string) {
slot := cast(s32)(NodeAppSlots - 1)
index := NodeAppIndex(slot)
saved_index := Packages.package_index
saved_release := Packages.package_release
saved_name := PackageText(NodeAppName(slot), "")
defer {
Packages.package_index = saved_index
Packages.package_release = saved_release
NodeAppAssign(slot, saved_name)
PackageFree(saved_name)
}
NodeAppAssign(slot, "parserprobe")
Packages.package_index = index
Packages.package_release.valid = true
unused DiaryTestHash(DiaryTestBytes(bytes), Packages.package_release.hash[:])
ModuleTestBlockParser(true)
Expect(AppsPreparePackage(index, bytes) == 0, 400)
for attempt: 0..5000 {
if ModuleTestParserStarted() { break }
ModuleTestYield()
}
Expect(ModuleTestParserStarted(), 401)
started := ModuleTestNow()
for frame: 0..99 {
Expect(AppsPreparePackage(index, bytes) == 0, 402)
}
AppsDiscardPreparation()
Expect(!AppsPreparationIdle() && ModuleTestNow() - started < 0.05, 403)
Expect(ListsRun(ListsMessage.{.action = LISTS_ROUTE, .screen = ScreenEList}).succeeded, 404)
ModuleTestBlockParser(false)
for attempt: 0..5000 {
if AppsPreparationIdle() { break }
ModuleTestYield()
}
Expect(AppsPreparationIdle(), 405)
// A Lists app is a valid ZX but cannot impersonate this node app.
Expect(ModuleTestPrepare(index, bytes) < 0 && AppsPreparationIdle(), 406)
}
#import, file "../src/apps/shared_state.zi";
#import, file "../src/apps/lists_types.zi";
#import, file "../src/apps/lists_visibility.zi";
#import, file "../src/apps/habits_types.zi";
#import, file "../src/apps/practice_types.zi";
#import, file "../src/apps/inbe_types.zi";
#import, file "../apps/diary/diary_types.zi";
Dates :: #import, file "../apps/diary/diary_date.zi";
#import, file "../src/apps/diary_store.zi";
#import, file "../src/apps/diary_records.zi";
#import, file "../src/apps/diary_blobs.zi";
#import, file "../src/apps/diary_photos.zi";
#import, file "../src/apps/media_store.zi";
#import, file "../src/apps/media_diary_photos.zi";
#import, file "../src/apps/entity_photos.zi";
#import, file "../src/storage/bundled_app_records.zi";
#import, file "../src/apps/package_files.zi";
#import, file "../src/app/app_types.zi";
#import, file "../src/core/types.zi";
#import, file "../src/core/breath_timing.zi";
#import, file "../src/practices/sun_salutation/sun_salutation_rules.zi";
#import, file "../src/storage/db.zi";
#import, file "../src/storage/data.zi";
#import, file "../src/storage/storage_core.zi";
#import, file "../src/storage/sync_state.zi";
#import, file "../src/storage/storage_settings.zi";
#import, file "../src/storage/storage_elist.zi";
#import, file "../src/storage/storage_habits.zi";
#import, file "../src/storage/storage_sessions.zi";
#import, file "../src/storage/state.zi";
#import, file "../src/storage/legacy_session_files.zi";
#import, file "../src/storage/legacy_session_time.zi";
#import, file "../src/storage/storage_thread_buffers.zi";
#import, file "../src/app/host_services.zi";
#import, file "../src/screens/elist_types.zi";
#import, file "../src/habits/habit_model.zi";
#import, file "../src/habits/habit_types.zi";
#import, file "../src/habits/habit_memory.zi";
#import, file "../src/app/text_buffers.zi";
#import, file "../src/app/app_size.zi";
#import "byte_text_linux"
#import "text_buffer"
#import "crypto"
#import, file "../src/app/assets.zi";
#import, file "../src/app/locale.zi";
#import, file "../src/storage/sync_node_storage.zi";
#import "file_linux"
#import, file "background_audio_stub.zi";
c :: #system_library "c";
ModuleTestText :: (name: string) -> string #foreign c;
ModuleTestCount :: (sql: string) -> s32 #foreign c;
ModuleTestSeedOld :: () -> bool #foreign c;
ModuleTestRuns :: () -> s32 #foreign c;
ModuleTestPackageBytes :: () -> bool #foreign c;
ModuleTestDiaryLockInheritance :: () -> bool #foreign c;
app: InnerBreeze;
list_id: [37]u8;
item_id: [37]u8;
user_id: [128]u8;
migrated_habit_id: [HABIT_ID_SIZE]u8;
edited_habit_id: [HABIT_ID_SIZE]u8;
failures: s32;
FindHabit :: (name: string) -> s32 {
index: s32 = 0
while index < app.habits.count {
if AppTextFromCString(*app.habits.items[index].name[0], HABIT_NAME_SIZE) == name {
return index
}
index += 1
}
return -1
}
Expect :: (ok: bool, code: s32) {
if !ok {
print("Module check failed: %\n", code)
if failures == 0 {
failures = code
}
}
}
CheckRootConfiguration :: () {
resources: [4]string = .["assets/lists/check.png", "assets/habits/leaf.png",
"assets/practices/breath.png", "assets/diary/calendar.png"]
kinds: [4]s32 = .[MODULE_LISTS, MODULE_HABITS, MODULE_PRACTICE, MODULE_DIARY]
for index: cast(s32)0..cast(s32)3 {
Expect(PackageResourceValid(resources[index], kinds[index]), 120 + index)
Expect(!PackageResourceValid(resources[index], kinds[(index + 1) % 4]), 124 + index)
}
unsafe: [8]string = .["assets/../apps/publishers.json", "assets//image.png",
"assets/image.png/", "/assets/image.png", "assets/./image.png",
"apps/publishers.json", "diary/2026-10-06.json", "assets/image:png"]
for index: cast(s32)0..cast(s32)7 {
Expect(!PackageResourceValid(unsafe[index], MODULE_INBE), 128 + index)
}
Expect(ModuleTestPackageBytes(), 74)
Expect(!AppsOpenPackage(""), 57)
Expect(!AppsOpenPackage(ModuleTestText("missing-assets")), 58)
Expect(!AppsOpenPackage(ModuleTestText("invalid-nested")), 59)
Expect(AppsOpenPackage(ModuleTestText("inbe")), 60)
// The apps open on their own threads; their assets read once they are open.
AppsFinishOpening()
Expect(AppsFeaturePackageSize(0) == ModuleTestText("inbe").count, 221)
names: [6]string = .["lists", "habits", "practice", "diary", "lumi", "leaderboard"]
for index: cast(s32)1..6 {
Expect(AppsFeaturePackageSize(index) == ModuleTestText(names[index - 1]).count, 222 + index)
}
Expect(AppsFeaturePackageSize(-1) == 0 && AppsFeaturePackageSize(7) == 0, 228)
size_text: [32]u8
Expect(AppBundleSizeText(66076, size_text[:]) &&
AppTextFromCString(*size_text[0], 32) == "66.1 kB", 230)
Expect(AppBundleSizeText(26131884, size_text[:]) &&
AppTextFromCString(*size_text[0], 32) == "26.1 MB", 231)
Expect(AppBundleSizeText(999950, size_text[:]) &&
AppTextFromCString(*size_text[0], 32) == "1.0 MB", 232)
Expect(!AppBundleSizeText(0, size_text[:]) && size_text[0] == cast(u8)0, 233)
// Practice pictures ship in each practice's pack; Wim Hof's pack ships
// with the app. Its card banner stays in Practices before installation.
shipped := AssetRead("assets/practices/default/whm.zx")
Expect(shipped.found && shipped.data.count > 8 && shipped.data[:2] == "ZX" &&
AssetRead("assets/practices/whm/banner-light.webp").found, 106)
language := AssetRead("locales/es.txt")
Expect(language.found && language.data.count > 1000, 107)
Expect(!AssetRead("apps/publishers.json").found, 108)
initial := InbeRun(InbeMessage.{.action = INBE_INITIAL_SCREEN,
.enabled_apps = APP_ALL, .screen = ScreenStart})
Expect(initial.succeeded && initial.screen == ScreenAudioSetup, 61)
initial.language_selected = true
initial = InbeRun(initial)
Expect(initial.succeeded && initial.screen == ScreenAppSelection, 62)
mask: s32 = 0
while mask <= APP_ALL {
Expect(AppsSetEnabled(mask) && AppsReady(), 63)
Expect(AppsInstalledMask() == APP_ALL, 219)
Expect(InbeAllows(ScreenLumi) &&
InbeAllows(ScreenEList) == ((mask & APP_LISTS) != 0) &&
InbeAllows(ScreenHabits) == ((mask & APP_HABITS) != 0) &&
InbeAllows(ScreenPatterns) == ((mask & APP_PRACTICE) != 0), 64)
Expect(InbeAllows(ScreenSettings) && InbeAllows(ScreenAppSelection), 65)
initial = InbeMessage.{.action = INBE_INITIAL_SCREEN,
.enabled_apps = mask, .screen = ScreenStart,
.language_selected = true, .apps_selected = true}
initial = InbeRun(initial)
expected: s32 = ScreenSettings
if (mask & APP_PRACTICE) != 0 {
expected = ScreenStart
} else if (mask & APP_LUMI) != 0 {
expected = ScreenLumi
} else if (mask & APP_HABITS) != 0 {
expected = ScreenHabits
} else if (mask & APP_LISTS) != 0 {
expected = ScreenEList
} else if (mask & APP_DIARY) != 0 {
expected = ScreenDiary
}
Expect(initial.succeeded && initial.screen == expected, 66)
if (mask & APP_LISTS) == 0 {
Expect(ListsRun(ListsMessage.{.action = LISTS_ROUTE,
.screen = ScreenEList}).succeeded, 67)
}
if (mask & APP_HABITS) == 0 {
Expect(HabitsRun(HabitsMessage.{.action = HABITS_ROUTE,
.screen = ScreenHabits}).succeeded, 68)
}
if (mask & APP_PRACTICE) == 0 {
Expect(PracticeRun(PracticeMessage.{.action = PRACTICE_ROUTE,
.screen = ScreenStart}).succeeded, 69)
}
mini := InbeRun(InbeMessage.{.action = INBE_MINI_CONFIGURE,
.enabled_apps = mask})
Expect(mini.succeeded && mini.enabled_apps == APP_PRACTICE &&
mini.screen == ScreenStart, 75)
Expect(AppsSetEnabled(mini.enabled_apps) &&
InbeAllows(ScreenStart) && !InbeAllows(ScreenEList), 76)
mini_session := PracticeRun(PracticeMessage.{
.action = PRACTICE_MEDITATION_STEP,
.remaining_seconds = 1, .elapsed_ms = 1000})
Expect(mini_session.succeeded && mini_session.completed, 77)
mask += 1
}
toggle := InbeRun(InbeMessage.{.action = INBE_TOGGLE_APP,
.enabled_apps = APP_ALL, .app = APP_PRACTICE, .checked = false})
Expect(toggle.succeeded && toggle.enabled_apps == (APP_ALL & ~APP_PRACTICE), 70)
toggle.app = APP_LISTS | APP_HABITS
Expect(!InbeRun(toggle).succeeded, 71)
Expect(AppsSetEnabled(APP_ALL), 72)
instances := ModuleTestInstanceOpens()
for frame: 0..199 {
unused frame
ready := ListsUiRun(ListsMessage.{.action = LISTS_ROUTE, .screen = ScreenEList})
root := InbeUiRun(InbeMessage.{.action = INBE_ROUTE, .screen = ScreenEList,
.enabled_apps = APP_ALL})
Expect(ready.succeeded && root.succeeded && root.allowed, 235)
}
Expect(ModuleTestInstanceOpens() == instances, 236)
ModuleTestFailRun()
failed := ListsUiRun(ListsMessage.{.action = LISTS_ROUTE, .screen = ScreenEList})
Expect(!failed.succeeded, 237)
ModuleTestFailInstantiate()
reset := ListsUiRun(ListsMessage.{.action = LISTS_ROUTE, .screen = ScreenEList})
Expect(!reset.succeeded && AppsReady(), 220)
recovered := ListsUiRun(ListsMessage.{.action = LISTS_ROUTE, .screen = ScreenEList})
Expect(recovered.succeeded && InbeAllows(ScreenEList), 238)
Expect(AppsFeaturePackageSize(1) == ModuleTestText("lists").count, 234)
runs := ModuleTestRuns()
Expect(InbeAllows(ScreenEList) && ModuleTestRuns() == runs + 2, 73)
}
CheckDiary :: () {
Expect(AppsValidatePackage(4, ModuleTestText("diary")), 80)
Expect(!AppsValidatePackage(4, ModuleTestText("habits")), 81)
// Diary may still be opening on its thread; frames must not reopen it.
AppsFinishOpening()
instances := ModuleTestInstanceOpens()
for frame: 0..49 {
unused frame
loaded := DiaryRun(DiaryMessage.{.action = DIARY_LOAD,
.year = 2024, .month = 2, .day = 28})
Expect(loaded.succeeded, 239)
}
Expect(ModuleTestInstanceOpens() == instances, 240)
state := DiaryRun(DiaryMessage.{.action = DIARY_LOAD, .year = 2024, .month = 2, .day = 28})
Expect(state.succeeded && state.saved && !state.load_error && state.text == "", 82)
Expect(ModuleTestDiaryLockInheritance(), 491)
state.action = DIARY_EDIT
state.replacement = "A calm day 🌿\nSecond line"
state = DiaryRun(state)
Expect(state.succeeded && !state.saved && state.text == "A calm day 🌿\nSecond line", 83)
// Routing must not overwrite unsaved text held by the editor.
Expect(InbeAllows(ScreenDiary), 84)
state.action = DIARY_CONTROL
state.control = 29002
state = DiaryRun(state)
Expect(state.succeeded && state.day == 29 && state.month == 2 && state.saved, 85)
loaded := DiaryRun(DiaryMessage.{.action = DIARY_LOAD, .year = 2024, .month = 2, .day = 28})
Expect(loaded.succeeded && loaded.text == "A calm day 🌿\nSecond line", 86)
loaded.action = DIARY_CONTROL
loaded.control = 29003
loaded = DiaryRun(loaded)
Expect(loaded.calendar && loaded.month_days == 29 && loaded.month_weekday == 3 && loaded.marks[28] == cast(u8)1, 87)
loaded.control = 29129
loaded = DiaryRun(loaded)
Expect(loaded.succeeded && !loaded.calendar && loaded.day == 29, 88)
Expect(!DiaryStoreSave("../outside.json", "invalid"), 89)
older := "{\"version\":1,\"date\":\"2024-03-01\",\"text\":\"Before\",\"photos\":[{\"file\":\"photo.png\",\"name\":\"Family\"}]}"
Expect(DiaryStoreSave("2024-03-01.json", older), 90)
// An older entry's photo is an embed after its text. Viewing the day
// writes nothing.
photo := DiaryRun(DiaryMessage.{.action = DIARY_LOAD, .year = 2024, .month = 3, .day = 1})
Expect(photo.saved && photo.text == "Before\n\n![Family](diary:photo.png)" &&
photo.cursor == cast(s32)photo.text.count && DiaryStoreRead("2024-03-01.json").data == older, 460)
photo.action = DIARY_EDIT
photo.edit_start = 6
photo.edit_end = 6
photo.replacement = " after"
photo = DiaryRun(photo)
photo.action = DIARY_SAVE
photo = DiaryRun(photo)
// Saving keeps the photo for older versions in "photos", derived from
// the embeds.
Expect(photo.saved && photo.document == "{\"version\":1,\"date\":\"2024-03-01\",\"text\":\"Before after\\n\\n![Family](diary:photo.png)\",\"photos\":[{\"file\":\"photo.png\",\"name\":\"Family\"}]}", 91)
// A photo added to the media library is embedded by its place there, on
// its own line at the caret, and saved at once. Older versions do not
// list it: it is no Diary file.
photo.action = DIARY_ATTACH
photo.cursor = 12
photo.anchor = 12
photo.attachment_file = "photos/2024/03/01/9f2c4e1a7b3d5f60718293a4b5c6d7e8f90123456789abcdef0123456789abcd.png"
photo.attachment_name = "A second photo 🌿"
photo = DiaryRun(photo)
Expect(photo.succeeded && photo.saved &&
photo.text == "Before after\n![A second photo 🌿](photos/2024/03/01/9f2c4e1a7b3d5f60718293a4b5c6d7e8f90123456789abcdef0123456789abcd.png)\n\n![Family](diary:photo.png)" &&
photo.document == "{\"version\":1,\"date\":\"2024-03-01\",\"text\":\"Before after\\n![A second photo 🌿](photos/2024/03/01/9f2c4e1a7b3d5f60718293a4b5c6d7e8f90123456789abcdef0123456789abcd.png)\\n\\n![Family](diary:photo.png)\",\"photos\":[{\"file\":\"photo.png\",\"name\":\"Family\"}]}", 461)
// Deleting an embed's line takes the photo out of the entry everywhere.
photo.action = DIARY_EDIT
photo.edit_start = 12 + 1 + 110
photo.edit_end = cast(s32)photo.text.count
photo.replacement = ""
photo = DiaryRun(photo)
photo.action = DIARY_SAVE
photo = DiaryRun(photo)
Expect(photo.saved && photo.text == "Before after\n![A second photo 🌿](photos/2024/03/01/9f2c4e1a7b3d5f60718293a4b5c6d7e8f90123456789abcdef0123456789abcd.png)" &&
photo.document == "{\"version\":1,\"date\":\"2024-03-01\",\"text\":\"Before after\\n![A second photo 🌿](photos/2024/03/01/9f2c4e1a7b3d5f60718293a4b5c6d7e8f90123456789abcdef0123456789abcd.png)\",\"photos\":[]}", 463)
photo.action = DIARY_ATTACH
photo.attachment_file = "diary:../outside.bin"
photo.attachment_name = "Invalid"
photo = DiaryRun(photo)
Expect(!photo.succeeded && photo.text == "Before after\n![A second photo 🌿](photos/2024/03/01/9f2c4e1a7b3d5f60718293a4b5c6d7e8f90123456789abcdef0123456789abcd.png)", 464)
photo = DiaryRun(DiaryMessage.{.action = DIARY_LOAD, .year = 2024, .month = 3, .day = 1})
Expect(photo.text == "Before after\n![A second photo 🌿](photos/2024/03/01/9f2c4e1a7b3d5f60718293a4b5c6d7e8f90123456789abcdef0123456789abcd.png)", 465)
// Older photo lists: brackets in names become spaces, a file listed
// twice is embedded once, and one the text embeds already is not added
// again. A photo an older version removed while its embed stayed comes
// back in "photos" on the next save.
Expect(DiaryStoreSave("2024-03-03.json", "{\"version\":1,\"date\":\"2024-03-03\",\"text\":\"x\\n![b](diary:b.png)\",\"photos\":[{\"file\":\"a.png\",\"name\":\"Fam[ily]\"},{\"file\":\"b.png\",\"name\":\"b\"},{\"file\":\"a.png\",\"name\":\"again\"}]}"), 466)
listed := DiaryRun(DiaryMessage.{.action = DIARY_LOAD, .year = 2024, .month = 3, .day = 3})
Expect(listed.text == "x\n![b](diary:b.png)\n![Fam ily ](diary:a.png)", 467)
Expect(DiaryStoreSave("2024-03-04.json", "{\"version\":1,\"date\":\"2024-03-04\",\"text\":\"![p](diary:p.png)\",\"photos\":[]}"), 468)
kept := DiaryRun(DiaryMessage.{.action = DIARY_LOAD, .year = 2024, .month = 3, .day = 4})
kept.action = DIARY_EDIT
kept.edit_start = 0
kept.edit_end = 0
kept.replacement = "Walk\n"
kept = DiaryRun(kept)
kept.action = DIARY_SAVE
kept = DiaryRun(kept)
Expect(kept.saved && kept.document == "{\"version\":1,\"date\":\"2024-03-04\",\"text\":\"Walk\\n![p](diary:p.png)\",\"photos\":[{\"file\":\"p.png\",\"name\":\"p\"}]}", 469)
// Photos inside a line of text: an older list's photo embedded there is
// not added again, saving lists each one in text order, and a photo
// attached at the end of a photo's line gets a line of its own.
Expect(DiaryStoreSave("2024-03-05.json", "{\"version\":1,\"date\":\"2024-03-05\",\"text\":\"Walk ![q](diary:q.png) and ![p](diary:p.png) home\",\"photos\":[{\"file\":\"p.png\",\"name\":\"p\"}]}"), 470)
inline_day := DiaryRun(DiaryMessage.{.action = DIARY_LOAD, .year = 2024, .month = 3, .day = 5})
Expect(inline_day.text == "Walk ![q](diary:q.png) and ![p](diary:p.png) home", 471)
inline_day.action = DIARY_EDIT
inline_day.edit_start = cast(s32)inline_day.text.count
inline_day.edit_end = inline_day.edit_start
inline_day.replacement = " today"
inline_day = DiaryRun(inline_day)
inline_day.action = DIARY_ATTACH
inline_day.attachment_file = "diary:r.png"
inline_day.attachment_name = "r"
inline_day = DiaryRun(inline_day)
Expect(inline_day.saved && inline_day.document == "{\"version\":1,\"date\":\"2024-03-05\",\"text\":\"Walk ![q](diary:q.png) and ![p](diary:p.png) home today\\n![r](diary:r.png)\\n\",\"photos\":[{\"file\":\"q.png\",\"name\":\"q\"},{\"file\":\"p.png\",\"name\":\"p\"},{\"file\":\"r.png\",\"name\":\"r\"}]}", 472)
// Text typed right after a photo keeps it in "photos".
inline_day.action = DIARY_EDIT
inline_day.edit_start = cast(s32)inline_day.text.count - 1
inline_day.edit_end = inline_day.edit_start
inline_day.replacement = " later"
inline_day = DiaryRun(inline_day)
inline_day.action = DIARY_SAVE
inline_day = DiaryRun(inline_day)
Expect(inline_day.saved && inline_day.text == "Walk ![q](diary:q.png) and ![p](diary:p.png) home today\n![r](diary:r.png) later\n" &&
inline_day.document == "{\"version\":1,\"date\":\"2024-03-05\",\"text\":\"Walk ![q](diary:q.png) and ![p](diary:p.png) home today\\n![r](diary:r.png) later\\n\",\"photos\":[{\"file\":\"q.png\",\"name\":\"q\"},{\"file\":\"p.png\",\"name\":\"p\"},{\"file\":\"r.png\",\"name\":\"r\"}]}", 473)
CheckDiaryPhotoOnFullNode()
CheckDiaryPhotoCopies()
CheckDiaryPhotosInLibrary()
Expect(DiaryStoreSave("2024-03-02.json", "damaged"), 92)
bad := DiaryRun(DiaryMessage.{.action = DIARY_LOAD, .year = 2024, .month = 3, .day = 2})
bad.action = DIARY_SAVE
Expect(bad.load_error && !DiaryRun(bad).succeeded, 93)
Expect(DiaryStoreRead("2024-03-02.json").data == "damaged", 94)
today := Dates.ParseDate(DiaryStoreClock()[:10])
tomorrow := Dates.Next(today, 1)
future := DiaryRun(DiaryMessage.{.action = DIARY_LOAD,
.year = tomorrow.year, .month = tomorrow.month, .day = tomorrow.day})
Expect(!future.succeeded, 410)
current := DiaryRun(DiaryMessage.{.action = DIARY_LOAD})
current.action = DIARY_EDIT
current.replacement = "Today's unsaved entry"
current = DiaryRun(current)
current.action = DIARY_CONTROL
current.control = 29002
current = DiaryRun(current)
Expect(!current.succeeded && current.day == today.day &&
current.month == today.month && current.year == today.year &&
current.text == "Today's unsaved entry" && !current.saved, 411)
current.control = 29003
current = DiaryRun(current)
current.control = 29012
current = DiaryRun(current)
Expect(!current.succeeded && current.calendar &&
current.month_year == today.year && current.month_number == today.month, 412)
if tomorrow.month == today.month {
current.control = 29100 + tomorrow.day
current = DiaryRun(current)
Expect(!current.succeeded && current.calendar && current.day == today.day, 413)
}
Expect(Dates.OnOrBefore(Dates.Date.{2024, 2, 29}, Dates.Date.{2024, 3, 1}) &&
!Dates.OnOrBefore(Dates.Date.{2024, 3, 1}, Dates.Date.{2024, 2, 29}) &&
!Dates.OnOrBefore(Dates.Date.{2023, 2, 29}, Dates.Date.{2024, 3, 1}) &&
Dates.OnOrBefore(Dates.Date.{2025, 12, 31}, Dates.Date.{2026, 1, 1}), 414)
current.action = DIARY_SAVE
current = DiaryRun(current)
Expect(current.saved && current.succeeded, 415)
original_owner := PackageText(AppTextFromCString(storage_user_id_buffer(), 64), "")
legacy := DiaryLegacyDirectory()
other: string = "different-diary-account"
AppCopyText(other, g_storage.user_id[:])
Expect(DiaryStoreRead("2024-02-28.json").missing, 416)
Expect(!DiaryStoreImportOwned(legacy), 417)
AppCopyText(original_owner, g_storage.user_id[:])
Expect(DiaryStoreRead("2024-02-28.json").data.count > 0, 418)
PackageFree(original_owner)
PackageFree(legacy)
}
// A photo always saves on this device: a sync node that reports no room
// only keeps the photo from syncing there.
CheckDiaryPhotoOnFullNode :: () {
node := "https://api.waozi.xyz"
sync_was_enabled := storage_sync_enabled()
storage_set_sync_enabled(1)
storage_set_setting_text("sync_server_url", node)
Expect(SyncNodeStorageRecordFull(node, "{\"code\":\"storage_full\",\"account_storage\":{\"used_bytes\":10485000,\"limit_bytes\":10485760}}") &&
SyncNodeStorageRead(node).full, 419)
png: [4096]u8
header: [8]u8 = .[cast(u8)137, cast(u8)80, cast(u8)78, cast(u8)71, cast(u8)13, cast(u8)10, cast(u8)26, cast(u8)10]
for index: cast(s32)0..cast(s32)4095 {
png[index] = ifx index < 8 then header[index] else cast(u8)(index % 251)
}
image := TextFromBytes(png[:])
source := "full-node-photo.png"
unused RemoveFile(source)
file := OpenExclusivePrivate(source)
written := file.valid && WriteTextAt(file, image, 0) == image.count
Expect(CloseFile(file) && written, 420)
name := DiaryStoreAttach(source)
Expect(name.count > 0 && DiaryStoreRead(name).data == image, 421)
PackageFree(name)
unused RemoveFile(source)
storage_set_setting_text("sync_server_url", "")
storage_set_sync_enabled(sync_was_enabled)
}
DiaryTestImage :: (bytes: []u8, seed: s32) -> string {
header: [8]u8 = .[cast(u8)137, cast(u8)80, cast(u8)78, cast(u8)71, cast(u8)13, cast(u8)10, cast(u8)26, cast(u8)10]
for index: cast(s32)0..cast(s32)bytes.count - 1 {
bytes[index] = ifx index < 8 then header[index] else cast(u8)((index * 7 + seed) % 251)
}
return TextFromBytes(bytes)
}
DiaryTestBytes :: (text: string) -> []u8 {
descriptor := cast(*TextDescriptor)(*text)
return BytesFromPointer(descriptor.data, cast(u64)text.count)
}
DiaryTestHash :: (data: []u8, output: []u8) -> string {
storage_sha256_hex(*data[0], cast(s64)data.count, *output[0])
return TextFromCString(*output[0])
}
// The pass's job for one photo's original, on any node or on the node at
// `node`, or 0; other Diary tests leave photos too.
DiaryTestNodeJob :: (pass: *DiaryBlobPass, key: string, node: string) -> s32 {
for index: cast(s32)0..pass.count - 1 {
address: [256]u8
unused DiaryBlobNode(pass, pass.jobs[index].node, address[:])
if TextUntilNul(pass.jobs[index].key[:]) == key && !pass.jobs[index].preview &&
(node.count == 0 || TextUntilNul(address[:]) == node) {
return pass.jobs[index].kind
}
}
return 0
}
DiaryTestJob :: (pass: *DiaryBlobPass, key: string) -> s32 {
return DiaryTestNodeJob(pass, key, "")
}
// The pass's request for one photo's original, skipping the others.
DiaryTestNext :: (pass: *DiaryBlobPass, request: *DiaryBlobRequest, key: string) -> bool {
while DiaryBlobNext(pass, request) {
if TextUntilNul(request.key[:]) == key && !request.preview {
return true
}
DiaryBlobAbandon(request)
DiaryBlobJobDone(pass)
}
return false
}
DiaryTestChunks :: (hash: string) -> EntityContent {
record := MediaEntityRecord(hash)
defer { PackageFree(record) }
return EntityPhotoContent(record)
}
// A photo travels as the account's entity data, sealed in chunks of its
// size plus 16 bytes, to a node and back to the account's devices.
CheckDiaryPhotoCopies :: () {
node := "https://copies.test"
sync_was_enabled := storage_sync_enabled()
storage_set_sync_enabled(1)
storage_set_setting_text("sync_server_url", node)
// The account key lets this device seal chunks.
private: [5121]u8
for index: cast(s32)0..cast(s32)5119 {
private[index] = ifx index % 2 == 0 then #char "a" else #char "7"
}
storage_set_setting_text(STORAGE_SYNC_PRIVATE_KEY_KEY, TextFromBytes(private[:5120]))
png: [3000]u8
image := DiaryTestImage(png[:], 3)
added := MediaImportBytes(image, "copied-photo.png")
Expect(added.succeeded && !added.existed, 430)
hash_text: [65]u8
hash := DiaryTestHash(png[:], hash_text[:])
key := EntityPhotoKey(hash)
Expect(TextFromBytes(added.hash[:64]) == hash, 431)
content := DiaryTestChunks(hash)
Expect(content.valid && content.chunk_count == 0 && content.size == 3000, 432)
no_copies := PackageText(PackageText("SELECT COUNT(*) FROM settings WHERE key GLOB 'cell.diary.chunk.", hash), ".*' OR key GLOB 'cell.media.*'")
Expect(ModuleTestCount(no_copies) == 0, 433)
PackageFree(no_copies)
// A pass seals and uploads it, then its record names the chunk.
pass: DiaryBlobPass
request: DiaryBlobRequest
Expect(DiaryBlobPlan(*pass, node) && DiaryTestJob(*pass, key) == DIARY_BLOB_UPLOAD, 434)
Expect(DiaryTestNext(*pass, *request, key) && request.method == "PUT" &&
request.body.count == image.count + 16 && request.body != image, 435)
sealed := PackageText(request.body, "")
blob_text: [65]u8
blob := DiaryTestHash(DiaryTestBytes(sealed), blob_text[:])
blob_path := PackageText("/api/v1/blobs/entity/", blob)
Expect(TextUntilNul(request.path[:]) == blob_path, 436)
Expect(DiaryBlobFinish(*pass, *request, 204, png[0:0]), 437)
DiaryBlobPassEnd(*pass)
content = DiaryTestChunks(hash)
Expect(content.chunk_count == 1 && TextUntilNul(content.chunks[0].address[:]) == blob &&
content.chunks[0].size == 3016, 438)
unused DiaryBlobPlan(*pass, node)
Expect(DiaryTestJob(*pass, key) == 0, 439)
DiaryBlobPassEnd(*pass)
// Another device of the account has only the record: the photo is not
// on the device until its chunks arrive, opened and checked.
path := MediaPath(hash, false)
unused RemoveFile(path)
MediaWant(hash)
Expect(!PathExists(path), 440)
Expect(DiaryBlobPlan(*pass, node) && DiaryTestJob(*pass, key) == DIARY_BLOB_DOWNLOAD, 441)
Expect(DiaryTestNext(*pass, *request, key) && request.method == "GET" &&
request.answer_bytes == sealed.count + 1, 442)
tampered := PackageText(sealed, "")
changed := DiaryTestBytes(tampered)
changed[20] = cast(u8)((cast(s32)changed[20] + 1) % 256)
generation := diary_blob_generation
Expect(DiaryBlobFinish(*pass, *request, 200, changed) &&
!PathExists(path) && diary_blob_generation == generation, 443)
DiaryBlobPassEnd(*pass)
Expect(DiaryBlobPlan(*pass, node) && DiaryTestNext(*pass, *request, key) &&
DiaryBlobFinish(*pass, *request, 404, png[0:0]) && !PathExists(path), 444)
DiaryBlobPassEnd(*pass)
Expect(DiaryBlobPlan(*pass, node) && DiaryTestNext(*pass, *request, key) &&
DiaryBlobFinish(*pass, *request, 200, DiaryTestBytes(sealed)) && diary_blob_generation > generation, 445)
DiaryBlobPassEnd(*pass)
Expect(PackageRead(path, DIARY_FILE_LIMIT) == image, 446)
// A new node gets the same chunk once.
other := "https://other-copies.test"
Expect(DiaryBlobPlan(*pass, other) && DiaryTestNodeJob(*pass, key, other) == DIARY_BLOB_UPLOAD, 447)
while DiaryTestNext(*pass, *request, key) && TextUntilNul(request.node[:]) != other {
DiaryBlobAbandon(*request)
DiaryBlobJobDone(*pass)
}
Expect(request.body == sealed, 448)
Expect(DiaryBlobFinish(*pass, *request, 204, png[0:0]), 449)
DiaryBlobPassEnd(*pass)
unused DiaryBlobPlan(*pass, other)
Expect(DiaryTestNodeJob(*pass, key, other) == 0, 459)
DiaryBlobPassEnd(*pass)
// A node without photo upload receives none; a full one stops uploads
// to it alone.
third := "https://third-copies.test"
Expect(SyncNodeSetMediaUpload(third, false), 450)
unused DiaryBlobPlan(*pass, third)
Expect(DiaryTestNodeJob(*pass, key, third) == 0, 450)
DiaryBlobPassEnd(*pass)
Expect(SyncNodeSetMediaUpload(third, true) && DiaryBlobPlan(*pass, third) &&
DiaryTestNodeJob(*pass, key, third) == DIARY_BLOB_UPLOAD, 451)
while DiaryTestNext(*pass, *request, key) && TextUntilNul(request.node[:]) != third {
DiaryBlobAbandon(*request)
DiaryBlobJobDone(*pass)
}
full := "{\"code\":\"storage_full\",\"account_storage\":{\"used_bytes\":20971000,\"limit_bytes\":20971520}}"
full_text := PackageText(full, "")
Expect(DiaryBlobFinish(*pass, *request, 413, DiaryTestBytes(full_text)) &&
pass.stopped[request.node_index] && SyncNodeStorageRead(third).full, 452)
DiaryBlobPassEnd(*pass)
PackageFree(full_text)
PackageFree(tampered)
PackageFree(blob_path)
PackageFree(sealed)
PackageFree(path)
PackageFree(key)
storage_set_setting_text(STORAGE_SYNC_PRIVATE_KEY_KEY, "")
storage_set_setting_text("sync_server_url", "")
storage_set_sync_enabled(sync_was_enabled)
}
// A Diary photo attached to a Diary file, saved, as older versions attach
// them; the caller frees its name.
DiaryLibraryAttach :: (bytes: []u8, seed: s32, source: string) -> string {
image := DiaryTestImage(bytes, seed)
unused RemoveFile(source)
file := OpenExclusivePrivate(source)
written := file.valid && WriteTextAt(file, image, 0) == image.count
Expect(CloseFile(file) && written, 480)
name := DiaryStoreAttach(source)
unused RemoveFile(source)
Expect(name.count > 0, 481)
return name
}
DiaryLibraryRun :: () {
for step: 0..63 {
unused step
unused MediaDiaryPhotosStep()
}
}
DiaryLibraryRecord :: (hash: string) -> string {
return MediaEntityRecord(hash)
}
// Photos older versions attached to Diary entries move to the account's
// entity data, which Photos shows, under the entry's day and with the
// entry's name. A Diary file no entry includes stays out, a photo in Trash
// stays there, and looking again changes nothing.
CheckDiaryPhotosInLibrary :: () {
first: [2600]u8
second: [2700]u8
orphan: [2800]u8
trashed: [2900]u8
later: [3100]u8
first_name := DiaryLibraryAttach(first[:], 11, "library-first.png")
second_name := DiaryLibraryAttach(second[:], 12, "library-second.png")
orphan_name := DiaryLibraryAttach(orphan[:], 13, "library-orphan.png")
trashed_name := DiaryLibraryAttach(trashed[:], 14, "library-trashed.png")
later_name := DiaryLibraryAttach(later[:], 15, "library-later.png")
first_hash_text: [65]u8
second_hash_text: [65]u8
orphan_hash_text: [65]u8
trashed_hash_text: [65]u8
later_hash_text: [65]u8
first_hash := DiaryTestHash(first[:], first_hash_text[:])
second_hash := DiaryTestHash(second[:], second_hash_text[:])
orphan_hash := DiaryTestHash(orphan[:], orphan_hash_text[:])
trashed_hash := DiaryTestHash(trashed[:], trashed_hash_text[:])
later_hash := DiaryTestHash(later[:], later_hash_text[:])
// One entry lists its photo, as older versions save it; another only
// embeds one in its text, as after an older version's Remove button.
first_out: Vec(u8)
BuilderPrint(*first_out, "{\"version\":1,\"date\":\"2024-04-02\",\"text\":\"Walk\",\"photos\":[{\"file\":\"%\",\"name\":\"IMG_2041.png\"}]}", first_name)
first_entry := BuilderFinish(first_out)
second_out: Vec(u8)
BuilderPrint(*second_out, "{\"version\":1,\"date\":\"2024-04-03\",\"text\":\"Tea\\n\\n![Tea cup](diary:%)\",\"photos\":[]}", second_name)
second_entry := BuilderFinish(second_out)
third_out: Vec(u8)
BuilderPrint(*third_out, "{\"version\":1,\"date\":\"2024-04-04\",\"text\":\"Rain\",\"photos\":[{\"file\":\"%\",\"name\":\"Rain\"},{\"file\":\"%\",\"name\":\"Later\"}]}", trashed_name, later_name)
third_entry := BuilderFinish(third_out)
Expect(DiaryStoreSave("2024-04-02.json", first_entry) && DiaryStoreSave("2024-04-03.json", second_entry) &&
DiaryStoreSave("2024-04-04.json", third_entry), 482)
// A photo the person moved to Trash in Photos stays there.
trashed_image := TextFromBytes(trashed[:])
Expect(MediaImportBytes(trashed_image, "Rain in Photos.png").succeeded &&
MediaSetTrashed(trashed_hash, true), 483)
trashed_record := DiaryLibraryRecord(trashed_hash)
// A photo whose file has not arrived on this device waits for it.
later_path := DiaryStorePath(later_name)
unused RemoveFile(later_path)
DiaryLibraryRun()
first_item := MediaRead(first_hash)
Expect(first_item.valid && !first_item.trashed && TextUntilNul(first_item.day[:]) == "2024-04-02" &&
TextUntilNul(first_item.taken[:]) == "2024-04-02" &&
TextUntilNul(first_item.name[:]) == "IMG_2041.png", 484)
second_item := MediaRead(second_hash)
Expect(second_item.valid && TextUntilNul(second_item.day[:]) == "2024-04-03" &&
TextUntilNul(second_item.name[:]) == "Tea cup", 485)
first_path := MediaPath(first_hash, false)
Expect(PackageRead(first_path, DIARY_FILE_LIMIT) == TextFromBytes(first[:]), 486)
Expect(!MediaRead(orphan_hash).valid && !MediaRead(later_hash).valid, 487)
trashed_now := DiaryLibraryRecord(trashed_hash)
Expect(trashed_now == trashed_record && MediaRead(trashed_hash).trashed, 488)
// Diary files of other checks belong to no entry either; the photo the
// copies check added is the fourth.
Expect(ModuleTestCount("SELECT COUNT(*) FROM settings WHERE key GLOB 'entity.photos.*' AND length(key)=78") == 4, 489)
Expect(DiaryStoreRead("2024-04-02.json").data == first_entry &&
DiaryStoreRead("2024-04-03.json").data == second_entry, 490)
// The entry's Diary file draws as the library's photo, so Diary's day
// lists that picture once.
diary_asset := PackageText(DiaryPhotoAsset(PackageText("diary:", first_name)), "")
place := MediaPlace(first_item)
Expect(diary_asset.count > 0 && diary_asset[:6] == "media/" && DiaryPhotoAsset(place) == diary_asset, 491)
// Its file arrives from a node.
Expect(PackageWrite(later_path, TextFromBytes(later[:])), 492)
diary_blob_generation += 1
DiaryLibraryRun()
later_item := MediaRead(later_hash)
Expect(later_item.valid && TextUntilNul(later_item.day[:]) == "2024-04-04" &&
TextUntilNul(later_item.name[:]) == "Later", 493)
// Looking again, as after a sync or a restart, changes nothing.
first_record := DiaryLibraryRecord(first_hash)
second_record := DiaryLibraryRecord(second_hash)
later_record := DiaryLibraryRecord(later_hash)
MediaDiaryPhotosDue()
DiaryLibraryRun()
media_diary_seen_valid = false
MediaDiaryPhotosDue()
DiaryLibraryRun()
first_again := DiaryLibraryRecord(first_hash)
second_again := DiaryLibraryRecord(second_hash)
later_again := DiaryLibraryRecord(later_hash)
trashed_again := DiaryLibraryRecord(trashed_hash)
Expect(first_again == first_record && second_again == second_record && later_again == later_record &&
trashed_again == trashed_record, 494)
Expect(ModuleTestCount("SELECT COUNT(*) FROM settings WHERE key GLOB 'entity.photos.*' AND length(key)=78") == 5, 495)
Expect(ModuleTestCount("SELECT COUNT(*) FROM settings WHERE key GLOB 'cell.media.*'") == 0, 499)
// The library's file is the Diary file, linked, not a second copy: a
// byte changed in place in one shows in the other.
diary_path := DiaryStorePath(first_name)
handle := OpenUpdate(diary_path)
marked: [1]u8 = .[cast(u8)7]
Expect(handle.valid && first[100] != cast(u8)7 && WriteAt(handle, marked[:], 100) == 1, 496)
linked := PackageRead(first_path, DIARY_FILE_LIMIT)
Expect(linked.count == first.count && linked[100] == cast(u8)7, 497)
marked[0] = first[100]
Expect(WriteAt(handle, marked[:], 100) == 1 && CloseFile(handle), 498)
PackageFree(linked)
PackageFree(diary_path)
PackageFree(first_again)
PackageFree(second_again)
PackageFree(later_again)
PackageFree(trashed_again)
PackageFree(first_record)
PackageFree(second_record)
PackageFree(later_record)
PackageFree(diary_asset)
PackageFree(place)
PackageFree(first_path)
PackageFree(trashed_now)
PackageFree(trashed_record)
PackageFree(later_path)
PackageFree(first_entry)
PackageFree(second_entry)
PackageFree(third_entry)
PackageFree(first_name)
PackageFree(second_name)
PackageFree(orphan_name)
PackageFree(trashed_name)
PackageFree(later_name)
}
CheckPackagedLocales :: () {
Expect(LocaleLanguageCount() == 12, 200)
for index: cast(s32)0..LocaleLanguageCount() - 1 {
Expect(PackagedLocaleMatches(LocaleLanguageAt(index).code), 201 + index)
}
// Leave a populated Japanese cache pointing into the old root, then
// replace it with freshly allocated package assets without switching locale.
Expect(LocaleUse("ja"), 213)
previous := LocaleText("close_button")
Expect(previous == "閉じる", 214)
Expect(AppsOpenPackage(ModuleTestText("inbe")), 215)
Expect(LocaleActiveCode() == "ja" && LocaleText("close_button") == "閉じる", 216)
Expect(PackagedLocaleMatches("ja"), 217)
Expect(LocaleUse("en"), 218)
}
#program_export
CheckModules :: () -> s32 {
lists := ModuleTestText("lists")
habits := ModuleTestText("habits")
practice := ModuleTestText("practice")
Expect(!AppsOpenBytes("", habits, practice), 1)
Expect(!AppsOpenBytes(lists, "ZX", practice), 2)
Expect(!AppsOpenBytes(habits, lists, practice), 3)
// Bind the actual shared persistence effects without opening user data.
unused AppsStart(*app)
Expect(AppsOpenBytes(lists, habits, practice), 4)
Expect(AppsFeaturePackageSize(1) == lists.count && AppsFeaturePackageSize(2) == habits.count &&
AppsFeaturePackageSize(3) == practice.count && AppsFeaturePackageSize(4) == 0, 229)
Expect(AppsRoute(ScreenEList) && AppsRoute(ScreenHabits) &&
AppsRoute(ScreenStart) && AppsRoute(ScreenMeditation) &&
!AppsRoute(ScreenSettings), 5)
CheckRootConfiguration()
CheckPackagedLocales()
Expect(ModuleTestSeedOld(), 6)
data_init()
Expect(storage_db_handle() != null, 7)
CheckNodeReloadRevisions(Expect)
AppCopyText(AppTextFromCString(storage_user_id_buffer(), 128), user_id[:])
CheckDiary()
habits_init_with_defaults(*app.habits, 0)
Expect(ModuleTestCount("SELECT COUNT(*) FROM sessions WHERE id='old-session'") == 1, 8)
Expect(ModuleTestCount("SELECT COUNT(*) FROM settings WHERE key='language' AND value='es'") == 1, 9)
// The existing upgrade rewrites non-UUID IDs together with their day rows.
Expect(ModuleTestCount("SELECT COUNT(*) FROM habits h JOIN habit_days d ON d.habit_id=h.id WHERE h.name='Old habit' AND h.user_id='module-user' AND length(h.id)=36 AND h.id<>'old-habit' AND d.local_date=20260925 AND d.completed=1 AND d.count=1") == 1, 10)
old_index := FindHabit("Old habit")
Expect(old_index >= 0, 44)
if old_index >= 0 {
AppCopyText(AppTextFromCString(*app.habits.items[old_index].id[0], HABIT_ID_SIZE), migrated_habit_id[:])
}
edit := ListsMessage.{.action = LISTS_COMMIT, .editing_item = -2, .title = "Trip"}
edit = ListsRun(edit)
Expect(edit.succeeded && edit.reload && edit.sync, 11)
AppCopyText(edit.selected_id, list_id[:])
unused storage_elist_load(cast(*void)*app.elist)
Expect(app.elist.list_count == 1, 12)
rename := ListsMessage.{.action = LISTS_COMMIT, .editing_item = -3,
.selected_list = 0, .list_count = 1,
.selected_id = AppTextFromCString(*list_id[0], 37),
.id = "00000000-0000-0000-0000-000000000000",
.title = "Trip renamed"}
rename = ListsRun(rename)
Expect(!rename.succeeded && rename.editing_item == -3 &&
rename.title == "Trip renamed" && !rename.reset_input, 275)
rename.id = AppTextFromCString(*list_id[0], 37)
rename = ListsRun(rename)
Expect(rename.succeeded && rename.editing_item == -1 && rename.reset_input, 276)
edit = ListsMessage.{.action = LISTS_COMMIT, .editing_item = -1,
.selected_list = 0, .list_count = 1, .selected_id = AppTextFromCString(*list_id[0], 37),
.title = "Passport"}
Expect(ListsRun(edit).succeeded, 13)
unused storage_elist_load(cast(*void)*app.elist)
AppCopyText(AppTextFromCString(*app.elist.items[0].id[0], 37), item_id[:])
edit.action = LISTS_SET_DONE
edit.id = AppTextFromCString(*item_id[0], 37)
edit.parent_id = AppTextFromCString(*list_id[0], 37)
edit.index = 0
edit.item_count = 1
edit.done = 1
edit.comment = "Keep relationship"
edit.now = 2.0
edit = ListsRun(edit)
Expect(edit.succeeded && edit.completing_until == 2.45, 14)
edit.action = LISTS_VISIBLE
edit = ListsRun(edit)
Expect(edit.visible, 15)
edit.now = 3.0
Expect(!ListsRun(edit).visible, 16)
unused storage_elist_load(cast(*void)*app.elist)
AppCopyText(AppTextFromCString(*item_id[0], 37), app.elist.completing_item[:])
app.elist.completing_until = 2.45
Expect(ListsRefreshVisibility(*app.elist, 2.1) && app.elist.item_visibility[0] && app.elist.visibility_deadline == 2.45, 51)
runs := ModuleTestRuns()
Expect(ListsRefreshVisibility(*app.elist, 2.2) && ModuleTestRuns() == runs, 52)
Expect(ListsRefreshVisibility(*app.elist, 2.5) && !app.elist.item_visibility[0] && ModuleTestRuns() == runs + 1, 53)
app.elist.show_completed = 1
Expect(ListsRefreshVisibility(*app.elist, 3.0) && app.elist.item_visibility[0] && ModuleTestRuns() == runs + 2, 54)
app.elist.show_completed = 0
unused storage_elist_load(cast(*void)*app.elist)
Expect(!app.elist.visibility_valid && ListsRefreshVisibility(*app.elist, 3.0) && !app.elist.item_visibility[0], 55)
// A returned text view lasts until the next call to that feature. This
// selection follows several visibility calls, so start a fresh message.
edit = ListsMessage.{.action = LISTS_SELECT, .index = 1, .list_count = 2}
edit = ListsRun(edit)
Expect(edit.selected_list == 1 && edit.reset_input && edit.reset_scroll && edit.show_completed == 0, 17)
habit := HabitsMessageFor(*app, HABITS_COMMIT)
habit.active = true
habit.is_new = true
habit.name = " \t "
habit = HabitsRun(habit)
Expect(habit.name_error == 1 && !habit.cancel_edit, 18)
// Reuse the rejected response, including its old validation error.
habit.name = "Reading"
habit.description = "Shared habit"
habit.weekdays = 127
habit.counter_enabled = 1
habit.counter_target = 3
habit.reminder_hour = 9
habit = HabitsRun(habit)
Expect(habit.succeeded && habit.name_error == 0 && habit.cancel_edit, 19)
habit.action = HABITS_COMMIT
habit.count = app.habits.count
habit.name = "Reading"
habit = HabitsRun(habit)
Expect(habit.name_error == 2, 20)
habit.name = "Writing"
habit = HabitsRun(habit)
Expect(habit.succeeded && habit.name_error == 0 && habit.cancel_edit, 21)
reading_index := FindHabit("Reading")
Expect(reading_index >= 0, 45)
if reading_index >= 0 {
AppCopyText(AppTextFromCString(*app.habits.items[reading_index].id[0], HABIT_ID_SIZE), edited_habit_id[:])
habit = HabitsMessageFor(*app, HABITS_COMMIT)
habit.active = true
habit.index = reading_index
habit.name = "Reading"
habit.description = "Edited through Habits bundle"
habit.counter_enabled = 1
habit.counter_target = 7
habit.weekdays = 31
habit = HabitsRun(habit)
Expect(habit.succeeded && habit.cancel_edit, 46)
Expect(ModuleTestCount("SELECT COUNT(*) FROM habits WHERE name='Reading' AND description='Edited through Habits bundle' AND counter_enabled=1 AND counter_target=7 AND weekdays=31") == 1, 47)
}
habit.action = HABITS_DAY_ACTION
habit.index = 0
habit.count = app.habits.count
habit.scheduled = true
habit.counter_enabled = 0
habit.linked_count = 1
habit.question_count = 2
habit = HabitsRun(habit)
Expect(habit.day_action == HABITS_DAY_LINKED && habit.block_click, 22)
habit.linked_count = 0
habit = HabitsRun(habit)
Expect(habit.day_action == HABITS_DAY_QUESTIONS && habit.block_click, 48)
habit.span = true
habit = HabitsRun(habit)
Expect(habit.day_action == HABITS_DAY_SPAN && habit.block_click, 50)
habit.span = false
habit.question_count = 0
habit = HabitsRun(habit)
Expect(habit.day_action == HABITS_DAY_TOGGLE, 49)
habit.action = HABITS_HISTORY
habit.selected = 0
habit = HabitsRun(habit)
Expect(habit.screen_mode == HABITS_SCREEN_HISTORY && habit.view_mode == HABIT_VIEW_CALENDAR, 23)
step := PracticeMessage.{.action = PRACTICE_MEDITATION_STEP,
.remaining_seconds = 2, .elapsed_ms = 1500}
step = PracticeRun(step)
Expect(step.succeeded && step.remaining_seconds == 1 && step.remainder_ms == 500 && !step.completed, 24)
step.paused = true
Expect(PracticeRun(step).remaining_seconds == 1, 25)
step.paused = false
step.elapsed_ms = 500
step = PracticeRun(step)
Expect(step.completed && step.remaining_seconds == 0, 26)
step = PracticeMessage.{.action = PRACTICE_BREATH_STEP}
step.breathing = BreathSessionInit()
step.breathing.phase = BreathPhaseNext
step.breathing.round = step.breathing.max_rounds - 1
step.breathing.breath_half_ticks = 1
i: s32 = 0
while i < 120 && !step.completed {
step = PracticeRun(step)
i += 1
}
Expect(step.succeeded && step.completed, 27)
step = PracticeMessage.{.action = PRACTICE_SALUTATION_STEP}
step.salutation = SalutationStart(SalutationInit(step.salutation))
step.elapsed = 1000.0
step = PracticeRun(step)
Expect(step.succeeded && step.completed, 28)
step = PracticeMessage.{.action = PRACTICE_PATTERNS_STEP}
step.patterns.active = 1
step.patterns.duration_minutes = 1
step.patterns.elapsed_seconds = 59
step = PracticeRun(step)
Expect(step.succeeded && step.completed && step.patterns.elapsed_seconds == 60, 29)
rounds: [1]s32 = .[42]
Expect(storage_save_session(*rounds[0], 1, null, 0) != 0, 30)
Expect(ModuleTestCount("SELECT COUNT(*) FROM elist_items i JOIN elist_lists l ON l.id=i.list_id WHERE i.user_id=l.user_id AND i.title='Passport' AND i.comment='Keep relationship' AND i.done=1") == 1, 31)
habits_free(*app.habits)
storage_close()
AppsClose()
Expect(AppsOpenPackage(ModuleTestText("inbe")), 32)
Expect(storage_init("module-data") != 0, 33)
Expect(AppTextFromCString(storage_user_id_buffer(), 128) == AppTextFromCString(*user_id[0], 128), 34)
unused storage_elist_load(cast(*void)*app.elist)
habits_init_with_defaults(*app.habits, 0)
Expect(app.elist.item_count == 1 && app.elist.items[0].done == 1 && app.habits.count >= 3, 35)
Expect(ModuleTestCount("SELECT COUNT(*) FROM sessions") == 2, 36)
Expect(ModuleTestCount("SELECT COUNT(DISTINCT entity_type) FROM sync_outbox WHERE entity_type IN ('elist_list','elist_item','habit','session')") == 4, 37)
Expect(ModuleTestCount("SELECT COUNT(*) FROM habits h JOIN habit_days d ON d.habit_id=h.id WHERE h.name='Old habit' AND h.user_id='module-user' AND length(h.id)=36 AND d.local_date=20260925 AND d.completed=1 AND d.count=1") == 1, 43)
old_index = FindHabit("Old habit")
reading_index = FindHabit("Reading")
Expect(old_index >= 0 && reading_index >= 0, 48)
if old_index >= 0 && reading_index >= 0 {
Expect(AppTextFromCString(*app.habits.items[old_index].id[0], HABIT_ID_SIZE) == AppTextFromCString(*migrated_habit_id[0], HABIT_ID_SIZE), 49)
Expect(AppTextFromCString(*app.habits.items[reading_index].id[0], HABIT_ID_SIZE) == AppTextFromCString(*edited_habit_id[0], HABIT_ID_SIZE) && app.habits.items[reading_index].counter_target == 7, 50)
}
// A valid bundle with a mismatched host schema must fail before saving.
Expect(AppsOpenBytes(ModuleTestText("wrong-record"), habits, practice), 38)
edit = ListsMessage.{.action = LISTS_COMMIT, .editing_item = -2, .title = "Unsafe"}
Expect(!ListsRun(edit).succeeded, 39)
Expect(ModuleTestCount("SELECT COUNT(*) FROM elist_lists") == 1, 40)
Expect(AppsOpenBytes(ModuleTestText("wrong-scalar"), habits, practice), 41)
Expect(!ListsRun(edit).succeeded, 42)
app.elist.visibility_valid = false
Expect(!ListsRefreshVisibility(*app.elist, 3.0), 56)
Expect(AppsOpenPackage(ModuleTestText("inbe")), 100)
lumi_result := CheckLumiConversation()
Expect(lumi_result == 0, lumi_result)
shop_result := CheckHabitShop()
Expect(shop_result == 0, 240 + shop_result)
list_result := CheckHabitList()
Expect(list_result == 0, 300 + list_result)
stats_result := CheckHabitStats()
Expect(stats_result == 0, 320 + stats_result)
home_result := CheckPracticeHome()
Expect(home_result == 0, 340 + home_result)
manual_result := CheckPracticeManual()
Expect(manual_result == 0, 360 + manual_result)
settings_result := CheckPracticeSettings()
Expect(settings_result == 0, 380 + settings_result)
results_result := CheckPracticeResults()
Expect(results_result == 0, 400 + results_result)
sessions_result := CheckPracticeSessions()
Expect(sessions_result == 0, 500 + sessions_result)
habits_free(*app.habits)
storage_close()
AppsClose()
ModuleTestUseCache(true)
cached_opens := ModuleTestBundleOpens()
Expect(AppsOpen(), 96)
// The root and its six apps, then the five cached app packages.
Expect(ModuleTestBundleOpens() - cached_opens == 12, 103)
for index: cast(s32)1..cast(s32)5 {
Expect(ModuleTestCachedReads(index) > 0, 97)
}
Expect(AppsInstalledMask() == APP_ALL, 98)
Expect(AppsFeaturePackageSize(1) == lists.count && AppsFeaturePackageSize(2) == habits.count, 235)
// Unrelated updates do not close/reopen working apps. A changed app is
// replaced transactionally, including a generic Diary with bound context.
unchanged_opens := ModuleTestBundleOpens()
unchanged_instances := ModuleTestInstanceOpens()
Expect(AppsReloadFeatures(APP_ALL), 251)
Expect(ModuleTestBundleOpens() == unchanged_opens &&
ModuleTestInstanceOpens() == unchanged_instances, 252)
habits_reads := ModuleTestCachedReads(2)
diary_reads := ModuleTestCachedReads(4)
ModuleTestSetRevision(1, 1)
ModuleTestCorruptCachedLists(true)
Expect(!AppsReloadFeatures(APP_ALL), 253)
Expect(ListsRun(ListsMessage.{.action = LISTS_ROUTE, .screen = ScreenEList}).succeeded, 254)
ModuleTestCorruptCachedLists(false)
Expect(AppsReloadFeatures(APP_ALL), 255)
Expect(ModuleTestCachedReads(2) == habits_reads && ModuleTestCachedReads(4) == diary_reads, 256)
ModuleTestSetRevision(4, 2)
Expect(AppsReloadFeatures(APP_ALL), 257)
Expect(ModuleTestCachedReads(2) == habits_reads && ModuleTestCachedReads(4) == diary_reads + 1, 258)
Expect(ModuleTestPrepare(0, ModuleTestText("inbe")) == 1, 259)
AppsDiscardPreparation()
Expect(AppsPreparationIdle(), 260)
Expect(ModuleTestPrepare(0, ModuleTestText("invalid-nested")) < 0, 261)
Expect(AppsPreparationIdle(), 262)
Expect(ModuleTestPrepare(1, lists) == 1, 263)
prepared_opens := ModuleTestBundleOpens()
prepared_reads := ModuleTestCachedReads(1)
AppsCommitPreparation(1, 3)
ModuleTestSetRevision(1, 3)
Expect(AppsReloadFeatures(APP_ALL), 264)
Expect(ModuleTestBundleOpens() == prepared_opens && ModuleTestCachedReads(1) == prepared_reads, 265)
Expect(ListsRun(ListsMessage.{.action = LISTS_ROUTE, .screen = ScreenEList}).succeeded, 266)
Expect(ModuleTestPrepare(4, ModuleTestText("diary")) == 1, 267)
AppsCommitPreparation(4, 4)
ModuleTestSetRevision(4, 4)
Expect(AppsReloadFeatures(APP_ALL) && DiaryRoute(ScreenDiary), 268)
ModuleTestBlockParser(true)
Expect(AppsPreparePackage(1, lists) == 0, 269)
for attempt: 0..5000 {
if ModuleTestParserStarted() { break }
ModuleTestYield()
}
Expect(ModuleTestParserStarted(), 270)
cancel_started := ModuleTestNow()
AppsDiscardPreparation()
Expect(!AppsPreparationIdle() && ModuleTestNow() - cancel_started < 0.05, 271)
Expect(ListsRun(ListsMessage.{.action = LISTS_ROUTE, .screen = ScreenEList}).succeeded, 272)
ModuleTestBlockParser(false)
for attempt: 0..5000 {
if AppsPreparationIdle() { break }
ModuleTestYield()
}
Expect(AppsPreparationIdle(), 273)
CheckNodePackagePreparation(lists)
ModuleTestSetRevision(1, 0)
ModuleTestSetRevision(4, 0)
AppsClose()
ModuleTestCorruptCachedLists(true)
Expect(AppsOpen() && AppsInstalledMask() == APP_ALL, 104)
Expect(AppsFeaturePackageSize(1) == lists.count, 236)
Expect(ListsRun(ListsMessage.{.action = LISTS_ROUTE, .screen = ScreenEList}).succeeded, 105)
AppsClose()
ModuleTestCorruptCachedLists(false)
ModuleTestUseCache(false)
before_opens := ModuleTestBundleOpens()
Expect(AppsOpenPackage(ModuleTestText("inbe")), 101)
AppsFinishOpening()
Expect(ModuleTestBundleOpens() - before_opens == 7, 102)
AppsClose()
Expect(AppsFeaturePackageSize(0) == 0 && AppsFeaturePackageSize(1) == 0, 237)
return failures
}