Skip to content
Tết −50%Đoàn Viên, only 99,500 VND first yearĐoàn Viên, first year only 99,500 VND, 1 personal reading a yearSee the offer

Blog

Test your Tử Vi or lunar calendar library against shared test cases

The test-case comparer run on a lunar calendar library, right and wrong versions

Nhat Nguyet's test cases are 17,291 input and answer pairs produced by the calculation engine that runs the site: anyone writing a Tử Vi, Bát Tự, numerology or lunar calendar library, in any language, can check against them. Nhat Nguyet's own TypeScript and Python versions must pass every case. This guide shows how to check your library.

What is in the test cases?

filecasescontent
am-lich.json14,936solar to lunar (11,039), lunar to solar (3,696), the 24 solar terms of each year (201), including the Chinese and Korean calendars
tu-vi.json777chart, ten-year periods, 2026 yearly period and flowing stars, patterns
bat-tu.json777four pillars, ten gods, luck periods, minor periods
than-so-hoc.json600numbers from full name and birth date
le-hoi.json201the solar date of each festival, every year from 1900 to 2100

Every file has the same layout:

Layout of ca-kiem/am-lich.json
Layout of ca-kiem/am-lich.json
  • phienBanDongCo: the engine version that produced the answers, currently 2.0.1.
  • khoaBo: 18 keys holding explanatory text (dienGiai, caveat, cachTinh...), removed at every level before comparing, because wording changes while the calculation does not.
  • ca: an array of {"vao", "ra"}; the inputs for each subject are listed in QUY-UOC.md in the repository.

Steps to compare

  1. Download the ca-kiem folder from the repository.
  2. Write a tinh(vao) function that calls your library and returns results with the same keys as ra.
  3. Remove the khoaBo keys on both sides, at every level.
  4. Compare deeply: key order does not matter, arrays compare in order, floats may differ by at most 1e-9, and a missing or extra key is a mismatch.
  5. Print the first mismatch with its key path, fix, and run again until everything passes.

The comparer in Python

import json, math, sys

def bo_khoa(v, bo):
    if isinstance(v, dict):
        return {k: bo_khoa(x, bo) for k, x in v.items() if k not in bo}
    if isinstance(v, list):
        return [bo_khoa(x, bo) for x in v]
    return v

def lech(mong, that, duong="ra"):
    if isinstance(mong, bool) or isinstance(that, bool):
        return None if mong is that else f"{duong}: expected {mong}, got {that}"
    if isinstance(mong, (int, float)) and isinstance(that, (int, float)):
        return None if abs(mong - that) <= 1e-9 else f"{duong}: expected {mong}, got {that}"
    if isinstance(mong, dict) and isinstance(that, dict):
        for k in sorted(set(mong) | set(that)):
            if k not in that or k not in mong:
                return f"{duong}.{k}: missing or extra key"
            r = lech(mong[k], that[k], f"{duong}.{k}")
            if r:
                return r
        return None
    if isinstance(mong, list) and isinstance(that, list):
        if len(mong) != len(that):
            return f"{duong}: độ dài expected {len(mong)}, got {len(that)}"
        for i, (a, b) in enumerate(zip(mong, that)):
            r = lech(a, b, f"{duong}[{i}]")
            if r:
                return r
        return None
    return None if mong == that else f"{duong}: expected {mong!r}, got {that!r}"

def kiem(mon, tinh, loc=lambda vao: True):
    tep = json.load(open(f"ca-kiem/{mon}.json", encoding="utf-8"))
    bo = set(tep["khoaBo"])
    dat = tong = 0
    for ca in tep["ca"]:
        if not loc(ca["vao"]):
            continue
        tong += 1
        r = lech(bo_khoa(ca["ra"], bo), bo_khoa(tinh(ca["vao"]), bo))
        if r is None:
            dat += 1
        elif tong - dat <= 3:
            print("  mismatch:", ca["vao"], r)
    print(f"{mon}: {dat}/{tong} cases pass")

Check the lunar calendar library, then a deliberately wrong version (it forgets the time zone and always computes at UTC+8):

from kiem_ca import kiem
from nhatnguyet import am_lich

def am_sang_duong(vao):
    duong, hop_le = am_lich.lunar_to_solar(vao["ngay"], vao["thang"], vao["nam"], vao["nhuan"], vao.get("muiGio", 7))
    return {"duong": duong, "hopLe": hop_le}

kiem("am-lich", am_sang_duong, lambda vao: vao["phep"] == "am-sang-duong")

# Try a wrong version: forgets the time zone, always UTC+8
def ban_sai(vao):
    duong, hop_le = am_lich.lunar_to_solar(vao["ngay"], vao["thang"], vao["nam"], vao["nhuan"], 8)
    return {"duong": duong, "hopLe": hop_le}

kiem("am-lich", ban_sai, lambda vao: vao["phep"] == "am-sang-duong")
am-lich: 3696/3696 cases pass
  mismatch: {'nam': 1914, 'ngay': 1, 'nhuan': False, 'phep': 'am-sang-duong', 'thang': 10} ra.duong.day: expected 17, got 18
  mismatch: {'nam': 1914, 'ngay': 15, 'nhuan': False, 'phep': 'am-sang-duong', 'thang': 10} ra.duong.day: expected 1, got 2
  mismatch: {'nam': 1914, 'ngay': 29, 'nhuan': False, 'phep': 'am-sang-duong', 'thang': 10} ra.duong.day: expected 15, got 16
am-lich: 3593/3696 cases pass
The Python comparer: the right version passes every case, the wrong one misses 103
The Python comparer: the right version passes every case, the wrong one misses 103

The right version passes 3,696/3,696. The wrong one passes 3,593, missing 103 cases, and the mismatch line points straight at the fault: ra.duong.day: expected 17, got 18, meaning the 1st of the 10th month of 1914 starts a day earlier in Vietnam time.

The same in TypeScript

import { readFileSync } from "node:fs";
import { lapLaSoTuVi, daiVan, tinhHanNam, tinhSaoLuu, nhanDienCachCuc } from "@nhatnguyet/tu-vi";

const tep = JSON.parse(readFileSync("ca-kiem/tu-vi.json", "utf8"));
const bo = new Set(tep.khoaBo);
const sach = (x) => Array.isArray(x) ? x.map(sach)
  : x && typeof x === "object" ? Object.fromEntries(Object.entries(x).filter(([k]) => !bo.has(k)).map(([k, v]) => [k, sach(v)]))
  : x;
function lech(a, b, duong = "ra") {
  if (typeof a === "number" && typeof b === "number") return Math.abs(a - b) <= 1e-9 ? null : `${duong}: expected ${a}, got ${b}`;
  if (Array.isArray(a) && Array.isArray(b)) {
    if (a.length !== b.length) return `${duong}: độ dài expected ${a.length}, got ${b.length}`;
    for (let i = 0; i < a.length; i++) { const r = lech(a[i], b[i], `${duong}.${i}`); if (r) return r; }
    return null;
  }
  if (a && b && typeof a === "object" && typeof b === "object") {
    for (const k of new Set([...Object.keys(a), ...Object.keys(b)])) {
      if (!(k in a) || !(k in b)) return `${duong}.${k}: missing or extra key`;
      const r = lech(a[k], b[k], `${duong}.${k}`); if (r) return r;
    }
    return null;
  }
  return a === b ? null : `${duong}: expected ${JSON.stringify(a)}, got ${JSON.stringify(b)}`;
}

let dat = 0;
for (const { vao, ra } of tep.ca) {
  const laSo = lapLaSoTuVi("", vao.gioiTinh, vao.dd, vao.mm, vao.yyyy, vao.gio);
  const kq = { laSo, daiVan: daiVan(laSo), hanNam: tinhHanNam(laSo, vao.namXem),
    saoLuu: tinhSaoLuu(laSo, vao.namXem), cachCuc: nhanDienCachCuc(laSo) };
  const r = lech(sach(ra), sach(JSON.parse(JSON.stringify(kq))));
  if (r) console.log("mismatch", vao, r); else dat++;
}
console.log(`tu-vi: ${dat}/${tep.ca.length} cases pass`);
tu-vi: 777/777 cases pass
The TypeScript comparer passing 777 of 777 Tử Vi cases
The TypeScript comparer passing 777 of 777 Tử Vi cases

What to do when a case fails

  • Read the key path first: a mismatch in ngaySinhAm is a calendar bug, one in cung is a star-placement bug.
  • Where schools differ, it is a convention, not a bug: the Tý hour from 23:00, the Four Transformations for the Canh stem, leap months. If your library chooses differently, document it and filter those cases.
  • If you think an answer is wrong, do not edit the test case: send your input and result to [email protected] and we will recheck the engine.

Passing every case means your library applies the school's rules exactly as Nhat Nguyet's engine does; it does not mean the rules of Tử Vi or Bát Tự hold true for a person's life, which has not been tested.

Licence

The test cases are CC BY 4.0 and the code MIT. Note in your README: "Test cases: Nhat Nguyet (nhatnguyet.org)". The code repository and test cases are on the open source page.

Open dataLunar calendar, sexagenary and festival datasets under CC BY 4.0.Try it

More from the blog

All blog posts