|
1 | | -from trackio.watchers import AlertReason, MetricWatcher, WatcherManager |
| 1 | +from trackio.watchers import ( |
| 2 | + AlertLevel, |
| 3 | + AlertReason, |
| 4 | + CustomMetricWatcher, |
| 5 | + MetricWatcher, |
| 6 | + WatcherManager, |
| 7 | +) |
2 | 8 |
|
3 | 9 |
|
4 | 10 | def test_nan_inf_triggers_stop(): |
@@ -108,3 +114,50 @@ def test_manager_should_stop_and_clear(): |
108 | 114 | def test_non_numeric_ignored(): |
109 | 115 | w = MetricWatcher("loss", max_value=10.0) |
110 | 116 | assert len(w.check("not a number", step=0)) == 0 |
| 117 | + |
| 118 | + |
| 119 | +def test_custom_watcher_bool_return(): |
| 120 | + w = CustomMetricWatcher("loss", fn=lambda v, s: v > 10.0) |
| 121 | + assert len(w.check(5.0, step=0)) == 0 |
| 122 | + alerts = w.check(15.0, step=1) |
| 123 | + assert len(alerts) == 1 |
| 124 | + assert alerts[0]["level"] == AlertLevel.WARN |
| 125 | + assert alerts[0]["data"]["reason"] == AlertReason.CUSTOM |
| 126 | + assert not w.should_stop |
| 127 | + |
| 128 | + |
| 129 | +def test_custom_watcher_dict_return_with_stop(): |
| 130 | + def fn(value, step): |
| 131 | + if value > 10.0: |
| 132 | + return [ |
| 133 | + { |
| 134 | + "title": "too high", |
| 135 | + "level": AlertLevel.ERROR, |
| 136 | + "stop": True, |
| 137 | + "data": {}, |
| 138 | + } |
| 139 | + ] |
| 140 | + return None |
| 141 | + |
| 142 | + w = CustomMetricWatcher("loss", fn=fn) |
| 143 | + assert len(w.check(5.0, step=0)) == 0 |
| 144 | + assert not w.should_stop |
| 145 | + alerts = w.check(15.0, step=1) |
| 146 | + assert len(alerts) == 1 |
| 147 | + assert alerts[0]["title"] == "too high" |
| 148 | + assert w.should_stop |
| 149 | + |
| 150 | + |
| 151 | +def test_custom_watcher_none_return(): |
| 152 | + w = CustomMetricWatcher("loss", fn=lambda v, s: None) |
| 153 | + assert len(w.check(99.0, step=0)) == 0 |
| 154 | + |
| 155 | + |
| 156 | +def test_manager_mixes_builtin_and_custom(): |
| 157 | + mgr = WatcherManager() |
| 158 | + mgr.add(MetricWatcher("loss", max_value=20.0)) |
| 159 | + mgr.add(CustomMetricWatcher("loss", fn=lambda v, s: v > 10.0)) |
| 160 | + alerts = mgr.check({"loss": 15.0}, step=0) |
| 161 | + assert len(alerts) == 1 |
| 162 | + alerts2 = mgr.check({"loss": 25.0}, step=1) |
| 163 | + assert len(alerts2) == 2 |
0 commit comments