Skip to content

The OSINT investigator's workbench. One case, one folder, every tool. Local-first: your media and your investigations never leave your machine.

JavaScript

Draw a date known only between two dates as a window, recut the Windows CI shards, and reframe the README tour (#101)

OsintMeThatb4d7b12fb0a4
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index f471467..aa2d358 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -42,25 +42,32 @@ jobs:
#
# Then measured again, because the box itself is not a constant: the same
# range ran 11 minutes one hour and 24 the next, and `test_repository.py`
- # alone is half of it. That range is split rather than trusted, since a
- # slow hour on the 30-minute timeout is a red run for no reason.
+ # holds a single test of four minutes. Its piece is kept lighter than the
+ # rest, since a slow hour on the 30-minute timeout is a red run for no reason.
#
- # These ranges look unbalanced by CPU seconds, and re-cutting them by that
- # number made the run worse rather than better: a split that put
- # `test_media_api.py` and `test_links_api.py` in one piece — even weight on
- # paper — failed the shard, because those two are where the suite contends
- # on locks and threads, and contention does not add up the way CPU seconds
- # do. `test_concurrent_sidecar_merges_do_not_drop_each_other` alone went to
- # two minutes there and the thread joins under it ran out. So the weight to
- # balance is Windows wall clock under `-n auto`, measured on Windows; a
- # Linux profile is not a stand-in for it, and cheap parallelism is not worth
- # a red run. Anyone re-cutting these should keep the lock-heavy files apart
- # and prove it on the box itself.
+ # Re-cutting by CPU seconds alone made the run worse rather than better: a
+ # split that put `test_media_api.py` and `test_links_api.py` in one piece —
+ # even weight on paper — failed the shard, because those two are where the
+ # suite contends on locks and threads, and contention does not add up the
+ # way CPU seconds do. `test_concurrent_sidecar_merges_do_not_drop_each_other`
+ # alone went to two minutes there and the thread joins under it ran out. So
+ # the weight to balance is Windows wall clock under `-n auto`, measured on
+ # Windows, and the lock-heavy files stay apart.
+ #
+ # The current cut comes from six runs of the previous one, where piece 1
+ # took 17 minutes and piece 4 took 7: each piece's wall clock, the slowest
+ # tests' own Windows times, and the rest from a Linux profile scaled by what
+ # its old piece measured. A piece holds several ranges, so a heavy letter
+ # no longer decides a job's length. Anyone re-cutting these should start
+ # from the `--durations` lines the Windows jobs print and prove it there.
#
# The ranges have to leave no gap: one stopping at test_sc* beside one
# starting at test_se* runs everything except the test_sd* somebody adds
- # next year, and says nothing. `tests/test_ci_shards.py` reads them back
- # out of this file and fails if they stop covering the directory.
+ # next year, and says nothing. A piece also stands on its own: a test file
+ # it imports is one it runs, and helpers two ranges share live in a helper
+ # module such as `tests/analyzerfixture.py`. `tests/test_ci_shards.py` reads
+ # the ranges back out of this file and fails on a gap, an overlap or a
+ # piece that imports another piece's test file.
include:
- name: Backend (ubuntu-latest, py3.12)
os: ubuntu-latest
@@ -73,31 +80,31 @@ jobs:
- name: Backend (windows-latest, py3.12, 1/7)
os: windows-latest
python: "3.12"
- tests: tests/test_[a-d]*.py tests/test_e[a-n]*.py
+ tests: tests/test_[a-b]*.py tests/test_[j-l]*.py tests/test_m[a-d]*.py
- name: Backend (windows-latest, py3.12, 2/7)
os: windows-latest
python: "3.12"
- tests: tests/test_e[o-z]*.py tests/test_[f-i]*.py
+ tests: tests/test_[c-f]*.py
- name: Backend (windows-latest, py3.12, 3/7)
os: windows-latest
python: "3.12"
- tests: tests/test_[j-o]*.py tests/test_p[a-l]*.py
+ tests: tests/test_[g-h]*.py tests/test_me*.py
- name: Backend (windows-latest, py3.12, 4/7)
os: windows-latest
python: "3.12"
- tests: tests/test_p[m-z]*.py
+ tests: tests/test_i*.py tests/test_t[i-z]*.py tests/test_[u-z]*.py
- name: Backend (windows-latest, py3.12, 5/7)
os: windows-latest
python: "3.12"
- tests: tests/test_[q-r]*.py tests/test_s[a-d]*.py
+ tests: tests/test_m[f-z]*.py tests/test_[n-p]*.py
- name: Backend (windows-latest, py3.12, 6/7)
os: windows-latest
python: "3.12"
- tests: tests/test_s[e-h]*.py
+ tests: tests/test_[q-r]*.py tests/test_s[a-g]*.py tests/test_t[a-h]*.py
- name: Backend (windows-latest, py3.12, 7/7)
os: windows-latest
python: "3.12"
- tests: tests/test_s[i-z]*.py tests/test_[t-z]*.py
+ tests: tests/test_s[h-z]*.py
- name: Backend (ubuntu-latest, py3.11)
os: ubuntu-latest
python: "3.11" # the floor in requires-python
diff --git a/README.md b/README.md
index 11eb978..29627a5 100644
--- a/README.md
+++ b/README.md
@@ -22,7 +22,13 @@
<a href="https://github.com/OsintMeThat/azimut/releases/latest"><img alt="Platforms" src="https://img.shields.io/badge/platforms-Windows%20%7C%20macOS%20%7C%20Linux-6b7280"></a>
</p>
-![A tour of Azimut: a clip downloaded into a case, examined and stitched, placed on satellite imagery, compared across dates, swept by Detect, then turned into a proof, a report and a note](https://raw.githubusercontent.com/OsintMeThat/azimut/main/docs/media/demo.gif)
+<p align="center">
+ <img
+ src="https://raw.githubusercontent.com/OsintMeThat/azimut/main/docs/media/demo.gif"
+ alt="A tour of Azimut's sixteen tools on one case: a clip downloaded, examined and stitched, placed on satellite imagery, compared across dates, swept by Detect, turned into a proof, a report and a note, then read on the Board, Timeline, Graph and Sheet"
+ width="800"
+ >
+</p>
## Install & run
diff --git a/docs/RELEASE_NOTES.md b/docs/RELEASE_NOTES.md
index 267de58..acc8c59 100644
--- a/docs/RELEASE_NOTES.md
+++ b/docs/RELEASE_NOTES.md
@@ -25,7 +25,8 @@ clearly what went wrong.
mentions, and its sources. **Add event** (Alt+N) opens the same line over any
tool, with that tool's view already cited.
- The Timeline draws each date as what it is: a point for an instant, a bracket
- for a day, a month or a year, a bar for a period. The axis and the list read as
+ for a day, a month or a year, a dashed line for something that happened once
+ between two dates, a bar for a period. The axis and the list read as
one, and a picked entry shows its media without opening it.
- Every date field has the same **Clock** chip: the place's zone, UTC, this
computer or any zone. A plain day can carry its zone too, and a new date reads
diff --git a/docs/UI.md b/docs/UI.md
index 2eae9f2..be1c960 100644
--- a/docs/UI.md
+++ b/docs/UI.md
@@ -1223,13 +1223,17 @@ answers a window wider than a month as cut rather than drawing stripes a few pix
wide.
Category tracks stack vertically. A mark is drawn where its date is, to the pixel, and
its shape says what kind of date it is: **a point is an instant, a bracket is a
-reduced date, a bar is a period**, and a box is never an instant. A reduced date is a
-thin line with a stop at each end, across the whole year, month or day it covers; once
-that period is narrower than a few pixels it is drawn as a point in its middle. A bar
-is as long as its period, down to two pixels, and a span running past the window has
+reduced date, a window is a moment known only between two dates, a bar is a period**,
+and a box is never an instant. A reduced date is a thin line with a stop at each end,
+across the whole year, month or day it covers; once that period is narrower than a few
+pixels it is drawn as a point in its middle. A window is the same line dashed: a range
+that occurred or was observed happened once, somewhere in it, so a video filmed between
+two dates never reads as lasting that long, and its date reads "between A and B". Only
+a range that held (Valid during) or one with no role is a bar. A bar is as long as its
+period, down to two pixels, and a span running past the window has
no stop on that side. Approximate dates have dashed ends, uncertain ones a broken or
hatched fill, a suggestion is hollow and a refuted statement is faded with its name
-struck. The legend names the three shapes and keeps date quality apart from assessment
+struck. The legend names the four shapes and keeps date quality apart from assessment
confidence, because the two are independent.
A mark never moves sideways for its neighbours or for what is selected. Marks that
diff --git a/docs/media/demo.gif b/docs/media/demo.gif
index e21a0ae..17776a0 100644
Binary files a/docs/media/demo.gif and b/docs/media/demo.gif differ
diff --git a/frontend/src/components/EntityTime.svelte b/frontend/src/components/EntityTime.svelte
index 30311d1..01a17d5 100644
--- a/frontend/src/components/EntityTime.svelte
+++ b/frontend/src/components/EntityTime.svelte
@@ -106,7 +106,7 @@
}
function timeLabel(item) {
- return formatTemporalValue(item.raw ?? '', item.tz).label;
+ return formatTemporalValue(item.raw ?? '', item.tz, item.time_role).label;
}
</script>
diff --git a/frontend/src/components/EntityTime.test.js b/frontend/src/components/EntityTime.test.js
index 07f10ab..3b2fcd7 100644
--- a/frontend/src/components/EntityTime.test.js
+++ b/frontend/src/components/EntityTime.test.js
@@ -49,7 +49,7 @@ describe('entity Time tab', () => {
});
it('uses the Timeline visual language and separates unresolved dates', () => {
- expect(source).toContain('formatTemporalValue(item.raw ?? \'\', item.tz).label');
+ expect(source).toContain('formatTemporalValue(item.raw ?? \'\', item.tz, item.time_role).label');
expect(source).toContain('var(--timeline-statement)');
expect(source).toContain('Not on UTC axis');
expect(source).toContain('Undated <span>{visibleUndated.length}</span>');
diff --git a/frontend/src/lib/fileDates.js b/frontend/src/lib/fileDates.js
index 32ba57d..3329296 100644
--- a/frontend/src/lib/fileDates.js
+++ b/frontend/src/lib/fileDates.js
@@ -52,7 +52,7 @@ function statedOffers(items, fileId) {
return {
kind,
value,
- words: `${kind} ${formatTemporalValue(value, item.tz).label}`,
+ words: `${kind} ${formatTemporalValue(value, item.tz, item.time_role).label}`,
hint: proof ? 'Use the date its proof gives' : 'Use the date already stated for this file',
};
})
diff --git a/frontend/src/lib/guide.js b/frontend/src/lib/guide.js
index 01ecb6e..f8146f8 100644
--- a/frontend/src/lib/guide.js
+++ b/frontend/src/lib/guide.js
@@ -332,7 +332,7 @@ export const GUIDE = [
},
{
label: 'Timeline puts your files where you dated them',
- text: 'Media draws a video or a picture at the date you gave it, on its proof or in an event about it; Events is every sentence you dated. Imagery and File dates wait under ⋯. A point is an instant, a bracket a date known to the day, month or year, a bar a period.',
+ text: 'Media draws a video or a picture at the date you gave it, on its proof or in an event about it; Events is every sentence you dated. Imagery and File dates wait under ⋯. A point is an instant, a bracket a date known to the day, month or year, a dashed line a moment known only between two dates, a bar a period.',
},
{
label: 'Sheet works on real CSV files',
diff --git a/frontend/src/lib/timeline.js b/frontend/src/lib/timeline.js
index a8138de..d853387 100644
--- a/frontend/src/lib/timeline.js
+++ b/frontend/src/lib/timeline.js
@@ -605,19 +605,35 @@ export function temporalZoneWords(item) {
}
}
+/**
+ * The time roles whose range is a window, not a duration: what occurred, or was seen,
+ * happened once, somewhere between the two dates. Only `valid` (a state that held)
+ * and a range with no role, such as a recording's own start and end, last.
+ */
+export const WINDOW_ROLES = new Set(['occurred', 'observed']);
+
+/** Whether a row's range is a window around one moment rather than a period. */
+export function isWindow(item) {
+ return item?.shape === 'interval' && WINDOW_ROLES.has(item?.time_role);
+}
+
/**
* A stored value in words. `tz` is the zone it was stated in, when it was: a day
* then names that zone, since the 12th in Kyiv is not UTC's 12th, and a time with
* no offset of its own reads on that zone's clock. A value stated in no zone reads
- * as it always has.
+ * as it always has. `role` is the statement's time role: a range that occurred or
+ * was observed reads "between A and B", since it happened once, not for that long.
*/
-export function formatTemporalValue(raw, tz = null) {
+export function formatTemporalValue(raw, tz = null, role = null) {
const check = validateTemporalValue(raw ?? '');
if (!raw) return { ...check, label: 'Undated', qualifiers: [] };
if (!check.valid) return { ...check, label: raw, qualifiers: [] };
const parts = raw.split('/');
const words = (part) => (DATE_TOKEN.test(part) ? dateLabel(part) : timestampLabel(part, tz));
- const base = parts.length === 2 ? `${words(parts[0])} to ${words(parts[1])}` : words(raw);
+ const range = WINDOW_ROLES.has(role)
+ ? `between ${words(parts[0])} and ${words(parts[1])}`
+ : `${words(parts[0])} to ${words(parts[1])}`;
+ const base = parts.length === 2 ? range : words(raw);
const label = tz && parts.some((part) => DATE_TOKEN.test(part)) ? `${base} (${tz})` : base;
return { ...check, label, qualifiers: qualifierLabels(raw) };
}
@@ -740,11 +756,14 @@ export function nudgeTemporalRaw(item, mode, direction) {
* How an entry is drawn on a track, in screen pixels.
*
* One rule decides the shape: **a point is an instant, a bracket is a reduced date, a
- * bar is a period, and a box is never an instant.** A date stated to the day, the month
- * or the year covers that whole period, so once the period is wide enough to see it is
- * drawn across it; narrower than `bracket` pixels it is as good as an instant and drawn
- * as one, in the middle of what it covers. A mark never moves because of its neighbours
- * or of what is selected: only its row does, and only when two marks would overlap.
+ * window is a moment known only between two dates, a bar is a period, and a box is
+ * never an instant.** A date stated to the day, the month or the year covers that whole
+ * period, so once the period is wide enough to see it is drawn across it; narrower than
+ * `bracket` pixels it is as good as an instant and drawn as one, in the middle of what
+ * it covers. A window is read the same way: a video filmed somewhere between two dates
+ * did not last that long, so it is never a bar. A mark never moves because of its
+ * neighbours or of what is selected: only its row does, and only when two marks would
+ * overlap.
*/
export const MARKS = {
top: 14,
@@ -785,10 +804,12 @@ function markOf(item, window, width) {
if (b <= 0 && a < 0) return null;
if (a >= width) return null;
const clipped = { openStart: a < 0, openEnd: b > width };
- if (item.shape === 'interval' || b - a >= MARKS.bracket) {
+ const period = item.shape === 'interval' && !isWindow(item);
+ if (period || b - a >= MARKS.bracket) {
const left = clamp(a, 0, width);
const right = Math.max(clamp(b, 0, width), left + MARKS.bar);
- return { mark: item.shape === 'interval' ? 'bar' : 'bracket', left, right, x: left, ...clipped };
+ const mark = period ? 'bar' : isWindow(item) ? 'window' : 'bracket';
+ return { mark, left, right, x: left, ...clipped };
}
const x = clamp((a + b) / 2, 0, width);
return { mark: 'point', left: x, right: x, x, openStart: false, openEnd: false };
@@ -861,7 +882,7 @@ function placeCards(placed, rowsTaken, width) {
}
const thumb = item.category === 'media' && item.thumb;
// The card holds the name and, under it, the date as written in the 9px mono face.
- const said = Math.ceil(formatTemporalValue(item.raw ?? '').label.length * 5.5);
+ const said = Math.ceil(formatTemporalValue(item.raw ?? '', null, item.time_role).label.length * 5.5);
const wide = clamp(
Math.max(captionWidth(item.label), said) + 20 + (thumb ? 38 : 0),
MARKS.cardMin,
diff --git a/frontend/src/lib/timeline.test.js b/frontend/src/lib/timeline.test.js
index 80410f1..7e09489 100644
--- a/frontend/src/lib/timeline.test.js
+++ b/frontend/src/lib/timeline.test.js
@@ -141,6 +141,14 @@ describe('temporal reading', () => {
.toBe('11 Aug 2026, 18:40:00 UTC+02:00');
expect(formatTemporalValue('2026-08-11/2026-08-14').label)
.toBe('11 Aug 2026 to 14 Aug 2026');
+ // What occurred or was seen happened once, between the two: never "for that long".
+ expect(formatTemporalValue('2022-03-24/2026-09-08', null, 'occurred').label)
+ .toBe('between 24 Mar 2022 and 8 Sep 2026');
+ expect(formatTemporalValue('2026-08-11/2026-08-14', null, 'observed').label)
+ .toBe('between 11 Aug 2026 and 14 Aug 2026');
+ expect(formatTemporalValue('2026-08-11/2026-08-14', null, 'valid').label)
+ .toBe('11 Aug 2026 to 14 Aug 2026');
+ expect(formatTemporalValue('2026-08-11', null, 'occurred').label).toBe('11 Aug 2026');
});
it('reads a camera clock to the millisecond at most, and not at all when it is zeros', () => {
@@ -230,6 +238,21 @@ describe('timeline layout', () => {
/ (Date.parse('2027-01-01') - Date.parse('2026-01-01'))) * 100, 5);
});
+ it('draws a moment known only between two dates as a window, never as a period', () => {
+ // A video filmed somewhere between the two dates did not last that long.
+ const range = (id, time_role) => ({ ...point(id, '2026-08-02T00:00:00Z', '2026-08-06T00:00:00Z', 'interval'), time_role });
+ const marks = Object.fromEntries(one([range('o', 'occurred'), range('s', 'observed'), range('v', 'valid'), range('n', null)])
+ .items.map((item) => [item.id, item]));
+ expect(Object.fromEntries(Object.entries(marks).map(([id, item]) => [id, item.mark])))
+ .toEqual({ o: 'window', s: 'window', v: 'bar', n: 'bar' });
+ expect(marks.o.left).toBeCloseTo(marks.v.left, 5);
+ expect(marks.o.width).toBeCloseTo(marks.v.width, 5);
+ // Narrower than a few pixels, a window is as good as an instant, like a reduced date.
+ const [narrow] = one([{ ...point('w', '2026-03-10T00:00:00Z', '2026-03-11T00:00:00Z', 'interval'), time_role: 'occurred' }],
+ '2026-01-01', '2026-12-31').items;
+ expect(narrow.mark).toBe('point');
+ });
+
it('draws a short period at its true length, never widened to a box', () => {
const [bar] = one([point('p', '2026-08-02T00:00:00Z', '2026-08-02T06:00:00Z', 'interval')]).items;
expect(bar.mark).toBe('bar');
diff --git a/frontend/src/lib/timelineCopy.js b/frontend/src/lib/timelineCopy.js
index 402094e..a219aef 100644
--- a/frontend/src/lib/timelineCopy.js
+++ b/frontend/src/lib/timelineCopy.js
@@ -40,7 +40,7 @@ export function chronologyRows(items = []) {
// The zone the date was stated in: without it a day written as the 12th
// cannot be told from UTC's 12th by someone reading the sheet alone.
zone: item.tz ?? '',
- reading: formatTemporalValue(item.raw ?? '', item.tz).label,
+ reading: formatTemporalValue(item.raw ?? '', item.tz, item.time_role).label,
earliest: item.earliest ?? '',
latest: item.latest ?? '',
statement: item.label ?? '',
diff --git a/frontend/src/lib/timelinePlate.js b/frontend/src/lib/timelinePlate.js
index 53386ef..cf34538 100644
--- a/frontend/src/lib/timelinePlate.js
+++ b/frontend/src/lib/timelinePlate.js
@@ -220,6 +220,13 @@ export function timelineDrawing({
fill: colour, opacity: hollow ? 0.08 : 0.3, stroke: colour, strokeWidth: 1,
dash: item.approximate ? '4 3' : (hollow ? '1.5 2' : undefined),
}));
+ } else if (item.mark === 'window') {
+ // A moment known only between two dates, dashed as on screen: it happened
+ // once in here, and the plate must not draw it as a period.
+ parts.push(svgLine({ x1: x, y1: middle, x2: x + span, y2: middle, stroke: colour, width: 1.5, dash: '4 3' }));
+ const stop = item.approximate ? '2 2' : undefined;
+ if (!item.openStart) parts.push(svgLine({ x1: x, y1: middle - 4, x2: x, y2: middle + 4, stroke: colour, width: 1.5, dash: stop }));
+ if (!item.openEnd) parts.push(svgLine({ x1: x + span, y1: middle - 4, x2: x + span, y2: middle + 4, stroke: colour, width: 1.5, dash: stop }));
} else if (item.mark === 'bracket') {
// The whole period a reduced date covers, as the thin line it is on screen:
// the entry is somewhere in here, and the plate must not claim a point.
@@ -262,7 +269,7 @@ export function timelineDrawing({
parts.push(svgText(fitLabel(item.label, item.card.width - 16), {
x: plotLeft + item.card.left + 8, y: cardY + 16, size: geometry.labelSize, weight: '600', fill: ink,
}));
- parts.push(svgText(fitLabel(formatTemporalValue(item.raw, item.tz).label, item.card.width - 16), {
+ parts.push(svgText(fitLabel(formatTemporalValue(item.raw, item.tz, item.time_role).label, item.card.width - 16), {
x: plotLeft + item.card.left + 8, y: cardY + 30, size: 9, fill: PLATE_COLOURS.hint,
}));
}
@@ -301,7 +308,7 @@ export function timelineDrawing({
const statement = width - geometry.right - (8 + geometry.listDate) - geometry.names;
for (const { item, track } of rows) {
bottom += geometry.listRow;
- parts.push(svgText(fitLabel(formatTemporalValue(item.raw, item.tz).label, geometry.listDate - 10), {
+ parts.push(svgText(fitLabel(formatTemporalValue(item.raw, item.tz, item.time_role).label, geometry.listDate - 10), {
x: 8, y: bottom, size: 9, fill: PLATE_COLOURS.label,
}));
parts.push(svgText(fitLabel(item.label, statement), {
diff --git a/frontend/src/lib/timelinePlate.test.js b/frontend/src/lib/timelinePlate.test.js
index e921aca..5208bb5 100644
--- a/frontend/src/lib/timelinePlate.test.js
+++ b/frontend/src/lib/timelinePlate.test.js
@@ -130,6 +130,17 @@ describe('serialising the timeline', () => {
]);
});
+ it('draws a moment known only between two dates dashed, never as a period', () => {
+ const filmed = [{ ...ITEMS[1], id: 'w1', label: 'Filmed after the warehouse went up', approximate: false, time_role: 'occurred' }];
+ const layout = track({ items: filmed }).layout;
+ const { body } = timelineDrawing(scene({ tracks: [track({ items: filmed })] }));
+
+ expect(layout.items.map((item) => item.mark)).toEqual(['window']);
+ expect(body).toMatch(/<line[^>]*stroke-dasharray="4 3"/);
+ expect(body).not.toMatch(/<rect[^>]*height="8"/);
+ expect(body).toContain('between 10 Mar 2026 and 18 Mar 2026');
+ });
+
it('marks a proposal hollow, the way every surface draws one', () => {
const suggested = [{ ...ITEMS[0], status: 'suggested' }];
const { body } = timelineDrawing(scene({ tracks: [track({ items: suggested })] }));
diff --git a/frontend/src/tools/Timeline.svelte b/frontend/src/tools/Timeline.svelte
index 73a81c4..e61deb7 100644
--- a/frontend/src/tools/Timeline.svelte
+++ b/frontend/src/tools/Timeline.svelte
@@ -354,7 +354,7 @@
* wide one half empty.
*/
const overviewTicks = $derived(densityTicks(overview, extent, overviewWidth));
- const selectedReading = $derived(formatTemporalValue(selected?.raw ?? '', selected?.tz));
+ const selectedReading = $derived(formatTemporalValue(selected?.raw ?? '', selected?.tz, selected?.time_role));
/** Whether an entry names an instant, which can be read on the axis's clock. A day
* has no hour, and printing 00:00 in another zone would invent one. */
function instantOnClock(item) {
@@ -1717,7 +1717,7 @@
}
function showItemTooltip(event, item) {
- const reading = formatTemporalValue(item.raw ?? '', item.tz);
+ const reading = formatTemporalValue(item.raw ?? '', item.tz, item.time_role);
tooltip = {
x: Math.min(window.innerWidth - 286, event.clientX + 12),
y: Math.min(window.innerHeight - 132, event.clientY + 12),
@@ -1758,7 +1758,7 @@
top: ruler.bottom - card.top + down,
height: Math.max(0, mark.top + mark.height / 2 - ruler.bottom),
at: Math.min(Math.max(middle, ruler.left + 90), ruler.right - 90) - card.left + across,
- label: formatTemporalValue(item.raw ?? '', item.tz).label,
+ label: formatTemporalValue(item.raw ?? '', item.tz, item.time_role).label,
};
}
@@ -2080,6 +2080,7 @@
<strong>Shape</strong>
<span><i class="sample shape-point"></i>Instant</span>
<span><i class="sample shape-bracket"></i>Reduced date, across what it covers</span>
+ <span><i class="sample shape-window"></i>Happened once, somewhere between two dates</span>
<span><i class="sample shape-bar"></i>Period</span>
<strong>Date quality</strong>
<span><i class="sample approximate"></i>Approximate date</span>
@@ -2309,8 +2310,9 @@
{@const editable = canDragTemporal(item) && !snapshotReading}
{@const markTop = MARKS.top + item.row * MARKS.row}
<!-- A point is an instant, a bracket a reduced date across what it
- covers, a bar a period at its true length. The caption and the
- card are the mark's own button, so reading one is clicking it. -->
+ covers, a dashed window a moment known only between two dates, a
+ bar a period at its true length. The caption and the card are the
+ mark's own button, so reading one is clicking it. -->
<div
class={`timeline-event ${item.category} ${item.mark}`}
class:as-file={item.asFile}
@@ -2337,7 +2339,7 @@
<button
class="event-select"
data-mark={item.id}
- aria-label={`${item.label}, ${formatTemporalValue(item.raw, item.tz).label}`}
+ aria-label={`${item.label}, ${formatTemporalValue(item.raw, item.tz, item.time_role).label}`}
onpointerdown={(event) => {
// Ctrl is the measure gesture, so it must not also start a drag
if (event.ctrlKey || event.metaKey) return;
@@ -2370,7 +2372,7 @@
{/if}
<span class="card-copy">
<strong dir="auto">{item.label}</strong>
- <small>{formatTemporalValue(item.raw, item.tz).label}</small>
+ <small>{formatTemporalValue(item.raw, item.tz, item.time_role).label}</small>
</span>
</span>
{/if}
@@ -2546,7 +2548,7 @@
>
<!-- An instant on the axis's clock, so the list and the ruler agree
about the hour; a day as it was stated, in its own zone. -->
- <span role="gridcell" class="list-date" title={`${formatTemporalValue(item.raw, item.tz).label} · ${item.raw}`}>{instantOnClock(item) ? clockReading(item.earliest, zone, { named: false }) : formatTemporalValue(item.raw, item.tz).label}</span>
+ <span role="gridcell" class="list-date" title={`${formatTemporalValue(item.raw, item.tz, item.time_role).label} · ${item.raw}`}>{instantOnClock(item) ? clockReading(item.earliest, zone, { named: false }) : formatTemporalValue(item.raw, item.tz, item.time_role).label}</span>
<span role="gridcell" class="list-copy"><span class={`category-dot ${item.category}`}></span><strong dir="auto">{item.label}</strong></span>
{#if listColumns.subjects}<span role="gridcell" class="list-links" dir="auto">{names(item.subject_entities)}</span>{/if}
{#if listColumns.places}<span role="gridcell" class="list-links" dir="auto">{names(item.place_entities)}</span>{/if}
@@ -2838,7 +2840,7 @@
<ConfirmDialog
title={!pendingEdit.item.raw ? 'Date this entry?' : pendingEdit.item.shape === 'interval' ? 'Change this period?' : 'Move this date?'}
message={pendingEdit.item.label}
- detail={`${pendingEdit.item.raw ? formatTemporalValue(pendingEdit.item.raw, pendingEdit.item.tz).label : 'Undated'} → ${formatTemporalValue(pendingEdit.raw, pendingEdit.zone === undefined ? pendingEdit.item.tz : pendingEdit.zone).label}`}
+ detail={`${pendingEdit.item.raw ? formatTemporalValue(pendingEdit.item.raw, pendingEdit.item.tz, pendingEdit.item.time_role).label : 'Undated'} → ${formatTemporalValue(pendingEdit.raw, pendingEdit.zone === undefined ? pendingEdit.item.tz : pendingEdit.zone, pendingEdit.item.time_role).label}`}
confirmLabel="Update date"
icon="clock"
busy={directSaving}
@@ -2948,6 +2950,7 @@
.sample.refuted::after { content: ''; position: absolute; left: 2px; right: 2px; top: 4px; border-top: 1px solid var(--text-2); transform: rotate(-8deg); }
.sample.shape-point { width: 8px; height: 8px; margin-inline: 10px; border: 0; border-radius: 50%; background: var(--track-statement); }
.sample.shape-bracket { height: 8px; border: 0; border-inline: 2px solid var(--track-statement); border-radius: 0; background: linear-gradient(to bottom, transparent 3px, var(--track-statement) 3px, var(--track-statement) 5px, transparent 5px); }
+ .sample.shape-window { height: 8px; border: 0; border-inline: 1.5px solid var(--track-statement); border-radius: 0; background: repeating-linear-gradient(90deg, var(--track-statement) 0 4px, transparent 4px 7px) center / 100% 1.5px no-repeat; }
.sample.shape-bar { height: 8px; border-radius: 2px; background: color-mix(in srgb, var(--track-statement) 32%, var(--bg-1)); }
.timeline-grid { min-height: 0; flex: 1; display: grid; grid-template-columns: minmax(0, 1fr); grid-template-rows: minmax(0, 1fr); }
.timeline-grid.inspecting { grid-template-columns: minmax(0, 1fr) 330px; }
@@ -3034,8 +3037,8 @@
.folded-note { position: absolute; top: 13px; left: 14px; color: var(--text-3); font-size: 9px; }
.draw-range { position: absolute; inset-block: 12px; z-index: 6; border: 1px solid color-mix(in srgb, var(--accent) 70%, transparent); border-radius: 4px; background: color-mix(in srgb, var(--accent) 14%, transparent); pointer-events: none; }
/* One row of marks is 18px: a point is an 8px dot centred on its instant, a bracket a
- 2px line with a stop at each end of the period a reduced date covers, a bar an 8px
- band as long as its period. Nothing is nudged sideways, so a mark sits exactly on
+ 2px line with a stop at each end of the period a reduced date covers, a window the
+ same line dashed, a bar an 8px band as long as its period. Nothing is nudged sideways, so a mark sits exactly on
its date whichever way the axis is scrolled. */
.timeline-event { --event-color: var(--track-tint, var(--track-statement)); position: absolute; z-index: 2; height: 18px; color: var(--text-1); }
.timeline-event.media, .timeline-event.as-file { --event-color: var(--track-tint, var(--track-media)); }
@@ -3048,20 +3051,24 @@
.point .event-shape { top: 5px; left: calc(50% - 4px); width: 8px; height: 8px; border-radius: 50%; background: var(--event-color); box-shadow: 0 0 0 1.5px var(--bg-1); }
.bracket .event-shape { inset: 5px 0; border-inline: 2px solid var(--event-color); background: linear-gradient(to bottom, transparent 3px, var(--event-color) 3px, var(--event-color) 5px, transparent 5px); }
.bar .event-shape { inset: 5px 0; border: 1px solid var(--event-color); border-radius: 2px; background: color-mix(in srgb, var(--event-color) 32%, var(--bg-1)); }
+ /* A window: one moment, somewhere between its stops. Dashed so it never reads as a period. */
+ .window .event-shape { inset: 5px 0; border-inline: 1.5px solid var(--event-color); background: repeating-linear-gradient(90deg, var(--event-color) 0 4px, transparent 4px 7px) center / 100% 1.5px no-repeat; }
/* A span running past the window has no stop on that side: it goes on. */
.bracket.open-start .event-shape { border-left-width: 0; }
.bracket.open-end .event-shape { border-right-width: 0; }
+ .window.open-start .event-shape { border-left-width: 0; }
+ .window.open-end .event-shape { border-right-width: 0; }
.bar.open-start .event-shape { border-left-style: dotted; border-top-left-radius: 0; border-bottom-left-radius: 0; }
.bar.open-end .event-shape { border-right-style: dotted; border-top-right-radius: 0; border-bottom-right-radius: 0; }
.timeline-event.approximate.point .event-shape { box-shadow: none; outline: 1.5px dashed var(--event-color); outline-offset: 1px; }
- .timeline-event.approximate.bracket .event-shape { border-inline-style: dashed; }
+ .timeline-event.approximate.bracket .event-shape, .timeline-event.approximate.window .event-shape { border-inline-style: dashed; }
.timeline-event.approximate.bar .event-shape { border-style: dashed; }
.timeline-event.uncertain.point .event-shape { background: repeating-linear-gradient(135deg, var(--event-color) 0 2px, var(--bg-1) 2px 3px); }
.timeline-event.uncertain.bracket .event-shape { background: repeating-linear-gradient(90deg, var(--event-color) 0 3px, transparent 3px 5px) center / 100% 2px no-repeat; }
.timeline-event.uncertain.bar .event-shape { background-image: repeating-linear-gradient(135deg, transparent, transparent 3px, color-mix(in srgb, var(--text-2) 22%, transparent) 3px, color-mix(in srgb, var(--text-2) 22%, transparent) 5px); }
/* A proposal is hollow, the way every surface draws one. */
.timeline-event.suggested.point .event-shape { border: 2px solid var(--event-color); background: var(--bg-1); }
- .timeline-event.suggested.bracket .event-shape { border-inline-style: dotted; opacity: .75; }
+ .timeline-event.suggested.bracket .event-shape, .timeline-event.suggested.window .event-shape { border-inline-style: dotted; opacity: .75; }
.timeline-event.suggested.bar .event-shape { border-style: dotted; background: color-mix(in srgb, var(--event-color) 10%, var(--bg-1)); }
.timeline-event.refuted { opacity: .55; }
.timeline-event.refuted .event-caption, .timeline-event.refuted .card-copy strong { text-decoration: line-through; text-decoration-thickness: 1px; }
@@ -3073,7 +3080,7 @@
.timeline-event.against .event-shape { outline: 1px dashed var(--text-2); outline-offset: 3px; }
.event-caption { position: absolute; top: 3px; height: 12px; box-sizing: content-box; overflow: hidden; color: var(--text-1); font-size: 10px; font-weight: 600; line-height: 12px; text-align: left; text-overflow: ellipsis; white-space: nowrap; }
.event-caption.left { text-align: right; }
- .bracket .event-caption.inside { padding: 0 3px; background: var(--bg-1); }
+ .bracket .event-caption.inside, .window .event-caption.inside { padding: 0 3px; background: var(--bg-1); }
/* A name inside a span interrupts its line rather than sitting on it, so it reads on
any tint. */
.bar .event-caption.inside { padding: 0 4px; border-radius: 3px; background: var(--bg-1); }
diff --git a/frontend/src/tools/Timeline.test.js b/frontend/src/tools/Timeline.test.js
index 6fdf70d..5a64da2 100644
--- a/frontend/src/tools/Timeline.test.js
+++ b/frontend/src/tools/Timeline.test.js
@@ -138,7 +138,7 @@ describe('Timeline workspace', () => {
it('offers readable events, a list view and an inspector while an entry is picked', () => {
expect(source).toContain("viewMode === 'list'");
- expect(source).toContain('formatTemporalValue(item.raw, item.tz).label');
+ expect(source).toContain('formatTemporalValue(item.raw, item.tz, item.time_role).label');
expect(source).toContain('class="timeline-tooltip"');
// one shape per kind of date, decided by the layout rather than by the zone
expect(source).toContain('class={`timeline-event ${item.category} ${item.mark}`}');
@@ -358,7 +358,7 @@ describe('one reading, the axis over the list', () => {
expect(source).toContain('grid-template-columns: var(--list-columns');
// an instant on the axis's clock, named in the heading, and a day as stated
expect(source).toContain("{zone === UTC ? 'Date' : `Date · ${zoneWords(zone).place} time`}");
- expect(source).toContain('instantOnClock(item) ? clockReading(item.earliest, zone, { named: false }) : formatTemporalValue(item.raw, item.tz).label');
+ expect(source).toContain('instantOnClock(item) ? clockReading(item.earliest, zone, { named: false }) : formatTemporalValue(item.raw, item.tz, item.time_role).label');
expect(source).toContain("flags.push({ id: 'unsourced', label: 'no source' })");
expect(source).toContain("flags.push({ id: 'unassessed', label: 'not assessed' })");
// only a Claim is asked for a source and an assessment
@@ -419,7 +419,7 @@ describe('reading a mark', () => {
it('draws a line up to the ruler with the date as written, for one end or both', () => {
expect(source).toContain("const lines = item.mark === 'point' ? [middle] : [mark.left, mark.right];");
expect(source).toContain('class="time-guide" aria-hidden="true"');
- expect(source).toContain("label: formatTemporalValue(item.raw ?? '', item.tz).label");
+ expect(source).toContain("label: formatTemporalValue(item.raw ?? '', item.tz, item.time_role).label");
expect(source).toContain('showGuide(event.currentTarget, item)');
});
@@ -514,7 +514,7 @@ describe('changing a picked entry’s date', () => {
});
it('says both dates in words, each on its clock, when it asks', () => {
- expect(source).toContain("detail={`${pendingEdit.item.raw ? formatTemporalValue(pendingEdit.item.raw, pendingEdit.item.tz).label : 'Undated'} → ${formatTemporalValue(pendingEdit.raw, pendingEdit.zone === undefined ? pendingEdit.item.tz : pendingEdit.zone).label}`}");
+ expect(source).toContain("detail={`${pendingEdit.item.raw ? formatTemporalValue(pendingEdit.item.raw, pendingEdit.item.tz, pendingEdit.item.time_role).label : 'Undated'} → ${formatTemporalValue(pendingEdit.raw, pendingEdit.zone === undefined ? pendingEdit.item.tz : pendingEdit.zone, pendingEdit.item.time_role).label}`}");
});
});
diff --git a/frontend/src/tools/board/BoardGroup.svelte b/frontend/src/tools/board/BoardGroup.svelte
index ae7d84d..04c0050 100644
--- a/frontend/src/tools/board/BoardGroup.svelte
+++ b/frontend/src/tools/board/BoardGroup.svelte
@@ -205,7 +205,7 @@
</td>
<td class="span">{said ? spanWords(said.first, said.last) : ''}</td>
{:else if eventsGroup}
- {@const when = formatTemporalValue(entity.attrs?.when ?? '', entity.attrs?.when_zone)}
+ {@const when = formatTemporalValue(entity.attrs?.when ?? '', entity.attrs?.when_zone, entity.attrs?.time_role)}
<td class="when" class:none={!entity.attrs?.when} title="When it happened, as written">
{when.label}
</td>
diff --git a/frontend/src/tools/satellite/TemporalPopup.svelte b/frontend/src/tools/satellite/TemporalPopup.svelte
index cfa195a..dfdd871 100644
--- a/frontend/src/tools/satellite/TemporalPopup.svelte
+++ b/frontend/src/tools/satellite/TemporalPopup.svelte
@@ -60,7 +60,7 @@
*/
function when(item) {
if (!item.raw) return '';
- if (!item.raw.includes('T')) return formatTemporalValue(item.raw, item.tz).label;
+ if (!item.raw.includes('T')) return formatTemporalValue(item.raw, item.tz, item.time_role).label;
const stamp = zonedStamp(item.earliest);
return stamp ? `${stamp.slice(8, 10)} ${stamp.slice(5, 7)} · ${stamp.slice(11, 16)}` : '';
}
diff --git a/tests/analyzerfixture.py b/tests/analyzerfixture.py
index 9fc2857..310cb32 100644
--- a/tests/analyzerfixture.py
+++ b/tests/analyzerfixture.py
@@ -11,8 +11,9 @@ import io
import numpy as np
from PIL import Image
-from azimut.engine import analyzers, sentinel, tilecache
+from azimut.engine import analyzers, sentinel, tilecache, workqueue
from azimut.engine.analysis_models import BUILTINS, RunInput, Source, product_for
+from azimut.workspace import Case
# One native Sentinel tile: level 13 of the 512px grid, 6.5 m a pixel at this latitude.
SENTINEL_TILE = (13, 4230, 2930)
@@ -23,6 +24,43 @@ EDGE = 512 + 2 * PAD
# Scene classes and the dark flag, as the fourth channel carries them.
VEGETATION, BARE, WATER, UNSURE, CLOUD, SHADOW = 4, 5, 6, 7, 9, 3
DARK = sentinel.DARK_FLAG
+# Sentinel-1: the radar layer and the hour of its pass.
+SAR_LAYER = "SAR_IW"
+SAR_TIME = "05:42:10"
+
+
+def sar_level(db):
+ """Decibels as the radar evalscript writes them: fifths of a dB above the floor."""
+ return np.clip(np.round((np.asarray(db, float) - sentinel.SAR_DB_FLOOR) / sentinel.SAR_DB_STEP),
+ 1, 255).astype(np.uint8)
+
+
+def analyzer_case(client, monkeypatch):
+ """A fresh case and a seeded sweep over it, with every network road shut."""
+ monkeypatch.setattr(workqueue, "start_workers", False)
+ ident = client.post("/api/cases", json={"name": "Analyzer tests"}).json()["id"]
+ case = Case.open(ident)
+ body = sample_input()
+ seed_images(body)
+
+ def forbidden(*args, **kwargs):
+ raise AssertionError("unexpected network")
+
+ monkeypatch.setattr(analyzers.httpx, "stream", forbidden)
+ monkeypatch.setattr(analyzers.sentinel, "band_frame", forbidden)
+ monkeypatch.setattr(analyzers.sentinel, "acquisitions", forbidden)
+ return case, body
+
+
+def run(client, case, body):
+ """Start a sweep, drain the queue, and read the finished run back."""
+ result = client.post(f"/api/cases/{case.id}/analysis/runs", json=body)
+ assert result.status_code == 200, result.text
+ if result.json().get("duplicates"):
+ result = client.post(f"/api/cases/{case.id}/analysis/runs", json={**result.json()["input"], "run_anyway": True})
+ assert result.status_code == 200, result.text
+ workqueue.drain(case)
+ return client.get(f"/api/cases/{case.id}/analysis/runs/{result.json()['id']}").json()
def zone(x0=.1, y0=.1, x1=.9, y1=.9, tile=SENTINEL_TILE, ident="patch"):
diff --git a/tests/fakeydl.py b/tests/fakeydl.py
new file mode 100644
index 0000000..9093b0b
--- /dev/null
+++ b/tests/fakeydl.py
@@ -0,0 +1,54 @@
+"""A stand-in for yt-dlp, so a download runs without a network."""
+
+import io
+import os
+import sys
+import types
+
+from PIL import Image
+
+
+def png_bytes(color=(200, 30, 30), size=(64, 48)) -> bytes:
+ buf = io.BytesIO()
+ Image.new("RGB", size, color).save(buf, "PNG")
+ return buf.getvalue()
+
+
+def install_fake_ydl(monkeypatch, extract_info_fn, content_fn=None):
+ """Patch a fake ``yt_dlp`` module. ``extract_info_fn(ydl, url, download)``
+ returns the info dict from the (single) ``extract_info`` call; ``prepare_filename``
+ writes a placeholder PNG next to the resolved name so ``download_url`` finds it
+ — ``content_fn(info)`` picks its bytes (default: identical for every call;
+ pass a per-``info`` variant to avoid sha256-dedup collisions across items
+ that are supposed to be distinct, e.g. in a concurrency test).
+ ``process_ie_result`` is a passthrough, matching the real "download from
+ already-extracted info, no second extraction" call ``download_url`` makes."""
+ content_fn = content_fn or (lambda info: png_bytes())
+
+ class FakeYDL:
+ def __init__(self, opts):
+ self.opts = opts
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *exc):
+ return False
+
+ def prepare_filename(self, info):
+ path = os.path.join(
+ os.path.dirname(self.opts["outtmpl"]), f"{info['title']} [{info['id']}].png"
+ )
+ with open(path, "wb") as fh:
+ fh.write(content_fn(info))
+ return path
+
+ def process_ie_result(self, info, download=True):
+ return info
+
+ def extract_info(self, url, download=False):
+ return extract_info_fn(self, url, download)
+
+ fake = types.ModuleType("yt_dlp")
+ fake.YoutubeDL = FakeYDL
+ monkeypatch.setitem(sys.modules, "yt_dlp", fake)
diff --git a/tests/stitchscene.py b/tests/stitchscene.py
new file mode 100644
index 0000000..76758ae
--- /dev/null
+++ b/tests/stitchscene.py
@@ -0,0 +1,53 @@
+"""Synthetic scenes for the auto-stitch gates.
+
+A textured scene to cut into overlapping crops, and views of one world through a
+camera turned by known angles, built by direct sampling so nothing under test is
+used to make its own input.
+"""
+
+import math
+import random
+
+from PIL import Image, ImageDraw
+
+
+def _scene(width=900, height=500, seed=7, blobs=220) -> Image.Image:
+ """A richly textured scene — random blobs give the detector real features."""
+ rng = random.Random(seed)
+ img = Image.new("RGB", (width, height), (18, 20, 28))
+ draw = ImageDraw.Draw(img)
+ for _ in range(blobs):
+ x, y = rng.randrange(width), rng.randrange(height)
+ r = rng.randrange(6, 34)
+ color = (rng.randrange(40, 255), rng.randrange(40, 255), rng.randrange(40, 255))
+ if rng.random() < 0.5:
+ draw.ellipse([x, y, x + r, y + r], fill=color)
+ else:
+ draw.rectangle([x, y, x + r, y + int(r * 0.7)], fill=color)
+ return img
+
+
+def _pan(angles, width=520, height=420, focal=520.0, seed=5) -> list[Image.Image]:
+ """Views of one world through a pinhole camera yawed by each of ``angles``.
+
+ The world is a 360°-wide cylindrical scene; each view samples it through the
+ camera's rays, which is exactly the situation the planar model cannot express
+ and the rotation model can.
+ """
+ import cv2
+ import numpy as np
+
+ world = np.asarray(_scene(4000, 900, seed=seed, blobs=3000))
+ wh, ww = world.shape[:2]
+ world_focal = ww / (2 * math.pi)
+
+ out = []
+ ys, xs = np.mgrid[0:height, 0:width].astype(np.float32)
+ for deg in angles:
+ x = (xs - width / 2) / focal
+ y = (ys - height / 2) / focal
+ theta = np.arctan2(x, np.ones_like(x)) + math.radians(deg)
+ map_x = ((theta * world_focal) % ww).astype(np.float32)
+ map_y = ((y / np.sqrt(x**2 + 1)) * world_focal + wh / 2).astype(np.float32)
+ out.append(Image.fromarray(cv2.remap(world, map_x, map_y, cv2.INTER_LINEAR)))
+ return out
diff --git a/tests/test_analyzers.py b/tests/test_analyzers.py
index dae535e..1230463 100644
--- a/tests/test_analyzers.py
+++ b/tests/test_analyzers.py
@@ -31,6 +31,7 @@ from analyzerfixture import (
UNSURE,
VEGETATION,
WATER,
+ analyzer_case,
at,
code,
fire_frame,
@@ -39,6 +40,7 @@ from analyzerfixture import (
hull,
index_byte,
index_frame,
+ run,
sample_input,
sea,
seed,
@@ -51,29 +53,7 @@ from analyzerfixture import (
@pytest.fixture
def scenario(client, monkeypatch):
- monkeypatch.setattr(workqueue, "start_workers", False)
- ident = client.post("/api/cases", json={"name": "Analyzer tests"}).json()["id"]
- case = Case.open(ident)
- body = sample_input()
- seed_images(body)
-
- def forbidden(*args, **kwargs):
- raise AssertionError("unexpected network")
-
- monkeypatch.setattr(analyzers.httpx, "stream", forbidden)
- monkeypatch.setattr(analyzers.sentinel, "band_frame", forbidden)
- monkeypatch.setattr(analyzers.sentinel, "acquisitions", forbidden)
- return case, body
-
-
-def run(client, case, body):
- result = client.post(f"/api/cases/{case.id}/analysis/runs", json=body)
- assert result.status_code == 200, result.text
- if result.json().get("duplicates"):
- result = client.post(f"/api/cases/{case.id}/analysis/runs", json={**result.json()["input"], "run_anyway": True})
- assert result.status_code == 200, result.text
- workqueue.drain(case)
- return client.get(f"/api/cases/{case.id}/analysis/runs/{result.json()['id']}").json()
+ return analyzer_case(client, monkeypatch)
# -- runs, review and evidence ------------------------------------------------------
diff --git a/tests/test_ci_shards.py b/tests/test_ci_shards.py
index 12c8408..7839148 100644
--- a/tests/test_ci_shards.py
+++ b/tests/test_ci_shards.py
@@ -31,6 +31,9 @@ TESTS = ROOT / "tests"
#: or more globs, which is what makes it a shard.
_TESTS_LINE = re.compile(r"^\s*tests:\s*(\S.*?)\s*$", re.MULTILINE)
+#: A test file reaching into another test file, at the top or inside a function.
+_TEST_IMPORT = re.compile(r"^\s*(?:from|import)\s+(test_\w+)", re.MULTILINE)
+
def _shards() -> list[list[str]]:
"""Every sharded `tests:` value in the workflow, as its list of globs."""
@@ -72,6 +75,26 @@ def test_no_test_file_runs_twice_on_windows(shards: list[list[str]]) -> None:
assert not twice, "these test files are in more than one Windows shard: " + ", ".join(twice)
+def test_no_shard_needs_a_test_file_another_shard_runs(shards: list[list[str]]) -> None:
+ """A shard stands on its own: the test files it imports are ones it runs itself.
+
+ The import works either way, so nothing fails when a cut separates two files that
+ share helpers. But the shard then loads a module some other job owns, and the cut
+ can no longer be moved without reading every file first. Helpers shared across
+ ranges belong in a helper module beside `conftest.py`, the way `analyzerfixture.py`
+ serves both the analyzer and the Detect tests.
+ """
+ home = {path.stem: i for i, globs in enumerate(shards) for glob in globs for path in ROOT.glob(glob)}
+ crossings = []
+ for path in sorted(TESTS.glob("test_*.py")):
+ for name in sorted(set(_TEST_IMPORT.findall(path.read_text(encoding="utf-8")))):
+ if name in home and home[name] != home.get(path.stem):
+ crossings.append(f"{path.name} imports {name}.py")
+ assert not crossings, (
+ "these Windows shards import a test file another shard runs: " + ", ".join(crossings)
+ )
+
+
def test_the_shards_stay_within_reach_of_each_other(shards: list[list[str]]) -> None:
"""No range grows into the one job everything waits for.
diff --git a/tests/test_detect_dating.py b/tests/test_detect_dating.py
index f20baed..9c85867 100644
--- a/tests/test_detect_dating.py
+++ b/tests/test_detect_dating.py
@@ -7,13 +7,12 @@ import pytest
from azimut import workspace
from azimut.engine import analysis_dating, maplayers, media
from azimut.workspace import Case
-from analyzerfixture import DAY_A, DAY_B, hull, sea, seed, sentinel_input
-from test_analyzers import run, scenario as analyzer_scenario
+from analyzerfixture import DAY_A, DAY_B, analyzer_case, hull, run, sea, seed, sentinel_input
@pytest.fixture
def scenario(client, monkeypatch):
- return analyzer_scenario.__wrapped__(client, monkeypatch)
+ return analyzer_case(client, monkeypatch)
def kept(client, case, saved, **pin):
diff --git a/tests/test_detect_rework.py b/tests/test_detect_rework.py
index aef1481..997f91c 100644
--- a/tests/test_detect_rework.py
+++ b/tests/test_detect_rework.py
@@ -12,13 +12,24 @@ from azimut import config, layout
from azimut.engine import analysis_geometry, analyzers, bundles, maplayers, media, workqueue
from azimut.engine.analysis_models import RunInput, Zone
from azimut.workspace import Case
-from analyzerfixture import SENTINEL_TILE, fire_frame, flame, hull, sea, seed, seed_images, sentinel_input, zone
-from test_analyzers import run, scenario as analyzer_scenario
+from analyzerfixture import (
+ SENTINEL_TILE,
+ analyzer_case,
+ fire_frame,
+ flame,
+ hull,
+ run,
+ sea,
+ seed,
+ seed_images,
+ sentinel_input,
+ zone,
+)
@pytest.fixture
def scenario(client, monkeypatch):
- return analyzer_scenario.__wrapped__(client, monkeypatch)
+ return analyzer_case(client, monkeypatch)
def area_body(raw):
diff --git a/tests/test_detect_rules.py b/tests/test_detect_rules.py
index 49a7435..eb7dd92 100644
--- a/tests/test_detect_rules.py
+++ b/tests/test_detect_rules.py
@@ -33,8 +33,22 @@ from azimut.engine.analysis_models import (
stored,
)
from azimut.workspace import Case
-from analyzerfixture import BARE, CLOUD, DARK, EDGE, SENTINEL_TILE, UNSURE, VEGETATION, WATER, at, put_picture, zone
-from test_radar_detect import LAYER, TIME, level
+from analyzerfixture import (
+ BARE,
+ CLOUD,
+ DARK,
+ EDGE,
+ SAR_LAYER,
+ SAR_TIME,
+ SENTINEL_TILE,
+ UNSURE,
+ VEGETATION,
+ WATER,
+ at,
+ put_picture,
+ sar_level,
+ zone,
+)
DAY_A, DAY_B = "2026-05-04", "2026-05-11"
LAT = 20.0
@@ -350,8 +364,8 @@ def test_radar_rules_average_speckle_as_power_and_read_both_passes():
def pass_(vv, vh):
frame = np.zeros((EDGE, EDGE, 4), np.uint8)
- frame[..., 0] = level(vv + rng.normal(0, 1.5, shape))
- frame[..., 1] = level(vh + rng.normal(0, 1.5, shape))
+ frame[..., 0] = sar_level(vv + rng.normal(0, 1.5, shape))
+ frame[..., 1] = sar_level(vh + rng.normal(0, 1.5, shape))
frame[..., 3] = 255
return frame
@@ -799,20 +813,20 @@ def test_a_check_needs_its_passes_and_the_track_they_share(client, offline):
body = {"recipe": built.model_dump(), "check": check_body([{"point": PLOT, "expect": "found"}], a={"date": ""})}
unpaired = client.post("/api/compare/analyzers/check", json=body)
assert unpaired.status_code == 422 and "before date" in unpaired.text
- client.put("/api/settings/prefs", json={"sentinel1_layer": LAYER})
+ client.put("/api/settings/prefs", json={"sentinel1_layer": SAR_LAYER})
radar = recipe({"measure": "radar", "on": "change", "op": "moved", "value": 3})
source = lambda day, time: {"provider": "sentinel1", "date": day, "time": time} # noqa: E731
marks = [{"point": PLOT, "expect": "found"}]
- crossed = check_body(marks, a=source(DAY_A, TIME), b=source(DAY_B, "17:40:00"))
+ crossed = check_body(marks, a=source(DAY_A, SAR_TIME), b=source(DAY_B, "17:40:00"))
refused = client.post("/api/compare/analyzers/check/plan", json={"recipe": radar.model_dump(), "check": crossed})
assert refused.status_code == 422 and "track" in refused.text
- same = check_body(marks, a=source(DAY_A, TIME), b=source(DAY_B, TIME))
+ same = check_body(marks, a=source(DAY_A, SAR_TIME), b=source(DAY_B, SAR_TIME))
assert client.post("/api/compare/analyzers/check/plan",
json={"recipe": radar.model_dump(), "check": same}).json() == {"tiles": 1, "missing": 2}
def test_a_check_saved_on_other_passes_asks_to_be_saved_again(client, offline):
- client.put("/api/settings/prefs", json={"sentinel1_layer": LAYER})
+ client.put("/api/settings/prefs", json={"sentinel1_layer": SAR_LAYER})
radar = recipe({"measure": "radar", "on": "change", "op": "moved", "value": 3})
answer = client.post("/api/compare/analyzers/check",
json={"recipe": radar.model_dump(), "check": check_body([{"point": PLOT, "expect": "found"}])})
diff --git a/tests/test_detect_saved_drift.py b/tests/test_detect_saved_drift.py
index 68f4762..d380201 100644
--- a/tests/test_detect_saved_drift.py
+++ b/tests/test_detect_saved_drift.py
@@ -13,13 +13,12 @@ import pytest
from azimut.engine import analyzers, media, workqueue
from azimut.engine.analysis_models import BUILTINS
-from analyzerfixture import seed_images
-from test_analyzers import run, scenario as analyzer_scenario
+from analyzerfixture import analyzer_case, run, seed_images
@pytest.fixture
def scenario(client, monkeypatch):
- return analyzer_scenario.__wrapped__(client, monkeypatch)
+ return analyzer_case(client, monkeypatch)
def rewrite(case, kind, ident, change):
diff --git a/tests/test_inspect_api.py b/tests/test_inspect_api.py
index 4c2afc4..bd21f92 100644
--- a/tests/test_inspect_api.py
+++ b/tests/test_inspect_api.py
@@ -563,7 +563,7 @@ def test_auto_stitch_rejects_unrelated_imagery(client):
def _pan_pngs(angles=(-20, 0, 20)):
"""Views of one world through a camera yawed by each angle, as PNG bytes."""
- from test_stitch import _pan
+ from stitchscene import _pan
out = []
for view in _pan(list(angles)):
diff --git a/tests/test_media_api.py b/tests/test_media_api.py
index 8072a84..19ce3cc 100644
--- a/tests/test_media_api.py
+++ b/tests/test_media_api.py
@@ -9,18 +9,13 @@ import graph_read
import pytest
import time
+from fakeydl import install_fake_ydl, png_bytes
from jobwait import WAIT, job_result, wait_for_job
from PIL import Image
from azimut.engine.media import safe_filename
-def _png_bytes(color=(200, 30, 30), size=(64, 48)) -> bytes:
- buf = io.BytesIO()
- Image.new("RGB", size, color).save(buf, "PNG")
- return buf.getvalue()
-
-
def _upload(client, cid, name, data, source_url=None):
return client.post(
f"/api/cases/{cid}/media/upload",
@@ -47,7 +42,7 @@ def test_safe_filename_sidesteps_the_windows_device_names():
def test_upload_and_list(client):
cid = client.post("/api/cases", json={"name": "Media"}).json()["id"]
- res = _upload(client, cid, "frame one.png", _png_bytes()).json()
+ res = _upload(client, cid, "frame one.png", png_bytes()).json()
assert res["duplicate"] is False
item = res["item"]
assert item["kind"] == "image"
@@ -72,7 +67,7 @@ def test_upload_and_list(client):
def test_media_list_reports_thumb_state(client):
cid = client.post("/api/cases", json={"name": "Thumbs"}).json()["id"]
- _upload(client, cid, "shot.png", _png_bytes())
+ _upload(client, cid, "shot.png", png_bytes())
item = client.get(f"/api/cases/{cid}/media").json()[0]
assert item["thumb_state"] == "ready" # image thumbnails render inline
@@ -84,7 +79,7 @@ def test_media_list_reports_enrichment_state(client, monkeypatch):
monkeypatch.setattr(workqueue, "start_workers", False)
cid = client.post("/api/cases", json={"name": "Enrichment state"}).json()["id"]
- _upload(client, cid, "shot.png", _png_bytes())
+ _upload(client, cid, "shot.png", png_bytes())
assert client.get(f"/api/cases/{cid}/media").json()[0]["enrich_state"] == "queued"
workqueue.drain(Case.open(cid))
@@ -121,7 +116,7 @@ def test_regenerate_queues_missing_thumbnails(client, monkeypatch):
monkeypatch.setattr(workqueue, "start_workers", False)
cid = client.post("/api/cases", json={"name": "Regen"}).json()["id"]
# an image whose cached thumbnail is then removed (as budget eviction would)
- item = _upload(client, cid, "shot.png", _png_bytes()).json()["item"]
+ item = _upload(client, cid, "shot.png", png_bytes()).json()["item"]
from azimut.workspace import Case
Case.open(cid).resolve_inside(item["thumbnail"]).unlink()
@@ -139,7 +134,7 @@ def test_enrich_backfill_queues_only_items_below_the_current_version(client, mon
monkeypatch.setattr(workqueue, "start_workers", False)
cid = client.post("/api/cases", json={"name": "Enrich backfill"}).json()["id"]
- rel = _upload(client, cid, "shot.png", _png_bytes()).json()["item"]["path"]
+ rel = _upload(client, cid, "shot.png", png_bytes()).json()["item"]["path"]
case = Case.open(cid)
workqueue.drain(case)
@@ -159,7 +154,7 @@ def test_enrich_backfill_can_force_one_known_path(client, monkeypatch):
monkeypatch.setattr(workqueue, "start_workers", False)
cid = client.post("/api/cases", json={"name": "Enrich one"}).json()["id"]
- rel = _upload(client, cid, "shot.png", _png_bytes()).json()["item"]["path"]
+ rel = _upload(client, cid, "shot.png", png_bytes()).json()["item"]["path"]
case = Case.open(cid)
workqueue.drain(case)
@@ -173,7 +168,7 @@ def test_listing_carries_category_fields(client):
"""The Media Library groups items into facets (Images/Videos/Imports/…) purely
from ``kind`` and ``source`` — guard that both survive upload + listing."""
cid = client.post("/api/cases", json={"name": "Facets"}).json()["id"]
- _upload(client, cid, "shot.png", _png_bytes())
+ _upload(client, cid, "shot.png", png_bytes())
item = client.get(f"/api/cases/{cid}/media").json()[0]
assert item["kind"] == "image" # drives the Images facet
@@ -208,7 +203,7 @@ def _set(client, cid, path, **patch):
def test_media_page_paginates(client):
cid = client.post("/api/cases", json={"name": "Page"}).json()["id"]
for i in range(5):
- _upload(client, cid, f"shot{i}.png", _png_bytes(color=(i, 0, 0)))
+ _upload(client, cid, f"shot{i}.png", png_bytes(color=(i, 0, 0)))
first = client.get(f"/api/cases/{cid}/media/page", params={"limit": 2}).json()
assert len(first["items"]) == 2
@@ -230,8 +225,8 @@ def test_media_page_paginates(client):
def test_media_page_query_matches_title_notes_folder(client):
cid = client.post("/api/cases", json={"name": "Q"}).json()["id"]
- a = _upload(client, cid, "alpha.png", _png_bytes(color=(1, 0, 0))).json()["item"]
- b = _upload(client, cid, "beta.png", _png_bytes(color=(2, 0, 0))).json()["item"]
+ a = _upload(client, cid, "alpha.png", png_bytes(color=(1, 0, 0))).json()["item"]
+ b = _upload(client, cid, "beta.png", png_bytes(color=(2, 0, 0))).json()["item"]
_set(client, cid, a["path"], notes="bridge over the river", folder="ukraine")
_set(client, cid, b["path"], title="Harbour view")
@@ -252,8 +247,8 @@ def test_media_page_query_matches_title_notes_folder(client):
def test_media_page_kind_and_folder_filters(client):
cid = client.post("/api/cases", json={"name": "Filt"}).json()["id"]
- a = _upload(client, cid, "a.png", _png_bytes(color=(3, 0, 0))).json()["item"]
- _upload(client, cid, "b.png", _png_bytes(color=(4, 0, 0)))
+ a = _upload(client, cid, "a.png", png_bytes(color=(3, 0, 0))).json()["item"]
+ _upload(client, cid, "b.png", png_bytes(color=(4, 0, 0)))
_set(client, cid, a["path"], folder="kyiv")
assert client.get(f"/api/cases/{cid}/media/page", params={"kind": "image"}).json()["total"] == 2
@@ -264,8 +259,8 @@ def test_media_page_kind_and_folder_filters(client):
def test_media_page_sort_name_and_size(client):
cid = client.post("/api/cases", json={"name": "Sort"}).json()["id"]
- small = _upload(client, cid, "s.png", _png_bytes(color=(5, 0, 0), size=(16, 16))).json()["item"]
- big = _upload(client, cid, "b.png", _png_bytes(color=(6, 0, 0), size=(256, 256))).json()["item"]
+ small = _upload(client, cid, "s.png", png_bytes(color=(5, 0, 0), size=(16, 16))).json()["item"]
+ big = _upload(client, cid, "b.png", png_bytes(color=(6, 0, 0), size=(256, 256))).json()["item"]
small = _set(client, cid, small["path"], title="Zebra")
big = _set(client, cid, big["path"], title="Alpha")
@@ -288,8 +283,8 @@ def test_media_page_sort_name_and_size(client):
def test_media_page_facets_count_full_set(client):
cid = client.post("/api/cases", json={"name": "Facets2"}).json()["id"]
- a = _upload(client, cid, "a.png", _png_bytes(color=(7, 0, 0))).json()["item"]
- _upload(client, cid, "b.png", _png_bytes(color=(8, 0, 0)))
+ a = _upload(client, cid, "a.png", png_bytes(color=(7, 0, 0))).json()["item"]
+ _upload(client, cid, "b.png", png_bytes(color=(8, 0, 0)))
_set(client, cid, a["path"], folder="kyiv")
# facets reflect the whole filtered set even when a page slices it
@@ -306,7 +301,7 @@ def test_media_page_filters_categories_without_page_local_counts(client):
from azimut.workspace import Case
cid = client.post("/api/cases", json={"name": "Categories"}).json()["id"]
- generic = _upload(client, cid, "generic.png", _png_bytes()).json()["item"]
+ generic = _upload(client, cid, "generic.png", png_bytes()).json()["item"]
satellite = media_engine.import_image(
Case.open(cid),
Image.new("RGB", (32, 24)),
@@ -333,7 +328,7 @@ def test_media_page_does_not_scan_sidecars_for_each_request(client, monkeypatch)
from azimut.engine import media as media_engine
cid = client.post("/api/cases", json={"name": "Indexed page"}).json()["id"]
- _upload(client, cid, "shot.png", _png_bytes())
+ _upload(client, cid, "shot.png", png_bytes())
monkeypatch.setattr(
media_engine,
"list_media",
@@ -380,7 +375,7 @@ def _made_here(client, cid, source_path, *, name=None):
def test_media_page_can_leave_out_what_the_case_made(client):
cid = client.post("/api/cases", json={"name": "Collected"}).json()["id"]
- original = _upload(client, cid, "orig.png", _png_bytes()).json()["item"]
+ original = _upload(client, cid, "orig.png", png_bytes()).json()["item"]
made = _made_here(client, cid, original["path"])
everything = client.get(f"/api/cases/{cid}/media/page").json()
@@ -400,7 +395,7 @@ def test_media_page_can_leave_out_what_the_case_made(client):
def test_leaving_them_out_scopes_the_counts_too(client):
"""Otherwise the Collages chip offers thirty rows and clicking it shows none."""
cid = client.post("/api/cases", json={"name": "Scoped counts"}).json()["id"]
- original = _upload(client, cid, "orig.png", _png_bytes()).json()["item"]
+ original = _upload(client, cid, "orig.png", png_bytes()).json()["item"]
_made_here(client, cid, original["path"])
page = client.get(f"/api/cases/{cid}/media/page", params={"collected_only": "true"}).json()
@@ -418,7 +413,7 @@ def test_a_capture_is_a_file_the_case_produced_itself(client):
from azimut.workspace import Case
cid = client.post("/api/cases", json={"name": "Untouched"}).json()["id"]
- upload = _upload(client, cid, "orig.png", _png_bytes()).json()["item"]
+ upload = _upload(client, cid, "orig.png", png_bytes()).json()["item"]
case = Case.open(cid)
media_engine.import_image(
case, Image.new("RGB", (32, 24)), "map.png",
@@ -440,7 +435,7 @@ def test_the_switch_reads_how_a_file_entered_not_everything_true_about_it(client
that arrived as an upload stay on the collected side even once Inspect produces
the same picture, because that is how they entered the case."""
cid = client.post("/api/cases", json={"name": "Entered by"}).json()["id"]
- original = _upload(client, cid, "orig.png", _png_bytes()).json()["item"]
+ original = _upload(client, cid, "orig.png", png_bytes()).json()["item"]
made = _made_here(client, cid, original["path"])
same_bytes = client.get(f"/files/{cid}/{made['path']}").content
@@ -458,7 +453,7 @@ def test_leaving_them_out_pages_and_counts_together(client):
have produced a right-looking first page and a wrong count under it."""
cid = client.post("/api/cases", json={"name": "Paged"}).json()["id"]
originals = [
- _upload(client, cid, f"orig{i}.png", _png_bytes(color=(40 + i * 40, 20, 20))).json()["item"]
+ _upload(client, cid, f"orig{i}.png", png_bytes(color=(40 + i * 40, 20, 20))).json()["item"]
for i in range(3)
]
for original in originals:
@@ -483,8 +478,8 @@ def test_leaving_them_out_pages_and_counts_together(client):
def test_media_metadata_returns_only_requested_paths(client):
cid = client.post("/api/cases", json={"name": "Metadata"}).json()["id"]
- first = _upload(client, cid, "first.png", _png_bytes(color=(10, 0, 0))).json()["item"]
- second = _upload(client, cid, "second.png", _png_bytes(color=(20, 0, 0))).json()["item"]
+ first = _upload(client, cid, "first.png", png_bytes(color=(10, 0, 0))).json()["item"]
+ second = _upload(client, cid, "second.png", png_bytes(color=(20, 0, 0))).json()["item"]
items = client.post(
f"/api/cases/{cid}/media/metadata",
@@ -496,7 +491,7 @@ def test_media_metadata_returns_only_requested_paths(client):
def test_media_page_items_carry_thumb_state(client):
cid = client.post("/api/cases", json={"name": "PageThumb"}).json()["id"]
- _upload(client, cid, "shot.png", _png_bytes())
+ _upload(client, cid, "shot.png", png_bytes())
page = client.get(f"/api/cases/{cid}/media/page").json()
assert page["items"][0]["thumb_state"] == "ready"
@@ -520,7 +515,7 @@ def test_media_page_reports_pending_thumbnails_beyond_the_loaded_page(client, mo
def test_duplicate_detection(client):
cid = client.post("/api/cases", json={"name": "Dup"}).json()["id"]
- data = _png_bytes(color=(1, 2, 3))
+ data = png_bytes(color=(1, 2, 3))
first = _upload(client, cid, "a.png", data).json()
second = _upload(client, cid, "b.png", data).json()
assert second["duplicate"] is True
@@ -530,7 +525,7 @@ def test_duplicate_detection(client):
def test_delete_media_removes_entity(client):
cid = client.post("/api/cases", json={"name": "Del"}).json()["id"]
- item = _upload(client, cid, "x.png", _png_bytes()).json()["item"]
+ item = _upload(client, cid, "x.png", png_bytes()).json()["item"]
client.delete(f"/api/cases/{cid}/media", params={"path": item["path"]})
assert client.get(f"/api/cases/{cid}/media").json() == []
assert graph_read.entities(cid) == []
@@ -548,7 +543,7 @@ def test_path_traversal_refused(client):
def test_update_media_notes_and_folder(client):
cid = client.post("/api/cases", json={"name": "Update"}).json()["id"]
- item = _upload(client, cid, "clip.png", _png_bytes()).json()["item"]
+ item = _upload(client, cid, "clip.png", png_bytes()).json()["item"]
updated = client.patch(
f"/api/cases/{cid}/media",
@@ -578,7 +573,7 @@ def test_update_media_title(client):
from azimut.workspace import Case
cid = client.post("/api/cases", json={"name": "Title"}).json()["id"]
- item = _upload(client, cid, "img.png", _png_bytes()).json()["item"]
+ item = _upload(client, cid, "img.png", png_bytes()).json()["item"]
updated = client.patch(
f"/api/cases/{cid}/media",
@@ -618,8 +613,8 @@ def test_media_rename_rewrites_exact_references_everywhere(client):
from azimut.workspace import Case
cid = client.post("/api/cases", json={"name": "Rename references"}).json()["id"]
- source = _upload(client, cid, "source.png", _png_bytes()).json()["item"]
- derived = _upload(client, cid, "derived.png", _png_bytes(color=(20, 40, 60))).json()["item"]
+ source = _upload(client, cid, "source.png", png_bytes()).json()["item"]
+ derived = _upload(client, cid, "derived.png", png_bytes(color=(20, 40, 60))).json()["item"]
case = Case.open(cid)
old = source["path"]
sentence = f"Analyst prose mentions {old} but is not a path field."
@@ -700,7 +695,7 @@ def test_media_rename_recovers_after_files_moved_before_database_update(client,
from azimut.workspace import Case
cid = client.post("/api/cases", json={"name": "Rename recovery"}).json()["id"]
- item = _upload(client, cid, "before.png", _png_bytes()).json()["item"]
+ item = _upload(client, cid, "before.png", png_bytes()).json()["item"]
case = Case.open(cid)
real_replace = Case.replace_path_references
@@ -730,12 +725,12 @@ def test_media_rename_takes_the_name_of_a_deleted_file(client):
# second rename onto "Shared" used to fail on the jobs' (kind, key) uniqueness
# after the file had already moved, leaving the entity on the old path.
cid = client.post("/api/cases", json={"name": "Rename over deleted"}).json()["id"]
- first = _upload(client, cid, "one.png", _png_bytes()).json()["item"]
+ first = _upload(client, cid, "one.png", png_bytes()).json()["item"]
renamed = client.patch(f"/api/cases/{cid}/media", json={"path": first["path"], "title": "Shared"})
assert renamed.status_code == 200
client.delete(f"/api/cases/{cid}/media", params={"path": "media/Shared.png"})
- second = _upload(client, cid, "two.png", _png_bytes(color=(90, 10, 10))).json()["item"]
+ second = _upload(client, cid, "two.png", png_bytes(color=(90, 10, 10))).json()["item"]
again = client.patch(f"/api/cases/{cid}/media", json={"path": second["path"], "title": "Shared"})
assert again.status_code == 200
@@ -746,8 +741,8 @@ def test_media_rename_takes_the_name_of_a_deleted_file(client):
def test_media_rename_uses_portable_case_insensitive_collisions(client):
cid = client.post("/api/cases", json={"name": "Portable names"}).json()["id"]
- _upload(client, cid, "Clip.png", _png_bytes()).json()["item"]
- other = _upload(client, cid, "other.png", _png_bytes(color=(90, 80, 70))).json()["item"]
+ _upload(client, cid, "Clip.png", png_bytes()).json()["item"]
+ other = _upload(client, cid, "other.png", png_bytes(color=(90, 80, 70))).json()["item"]
renamed = _set(client, cid, other["path"], title="clip")
@@ -757,7 +752,7 @@ def test_media_rename_uses_portable_case_insensitive_collisions(client):
def test_update_media_clear_notes(client):
cid = client.post("/api/cases", json={"name": "Clear"}).json()["id"]
- item = _upload(client, cid, "img.png", _png_bytes()).json()["item"]
+ item = _upload(client, cid, "img.png", png_bytes()).json()["item"]
client.patch(f"/api/cases/{cid}/media", json={"path": item["path"], "notes": "initial"})
updated = client.patch(
@@ -776,7 +771,7 @@ def test_import_states_where_the_file_came_from(client):
"""
cid = client.post("/api/cases", json={"name": "Stated"}).json()["id"]
item = _upload(
- client, cid, "shot.png", _png_bytes(), source_url="https://t.me/channel/42"
+ client, cid, "shot.png", png_bytes(), source_url="https://t.me/channel/42"
).json()["item"]
assert item["source"] == {
@@ -800,7 +795,7 @@ def test_import_states_where_the_file_came_from(client):
def test_a_stated_source_must_be_a_link(client):
cid = client.post("/api/cases", json={"name": "Not a link"}).json()["id"]
- res = _upload(client, cid, "shot.png", _png_bytes(), source_url="a friend sent it")
+ res = _upload(client, cid, "shot.png", png_bytes(), source_url="a friend sent it")
assert res.status_code == 422
assert client.get(f"/api/cases/{cid}/media").json() == []
@@ -809,7 +804,7 @@ def test_a_source_can_be_stated_after_the_import(client):
"""The origin is often remembered after the files have landed — and for a batch
dropped in one go, stated once for all of them."""
cid = client.post("/api/cases", json={"name": "Later"}).json()["id"]
- item = _upload(client, cid, "shot.png", _png_bytes()).json()["item"]
+ item = _upload(client, cid, "shot.png", png_bytes()).json()["item"]
updated = _set(client, cid, item["path"], source_url="https://example.org/post/7")
assert updated["source"]["url"] == "https://example.org/post/7"
@@ -908,7 +903,7 @@ def test_download_captures_description(client, monkeypatch):
path = os.path.join(os.path.dirname(self._tmpl), f"{info['title']} [{info['id']}].png")
with open(path, "wb") as fh:
- fh.write(_png_bytes())
+ fh.write(png_bytes())
return path
def process_ie_result(self, info, download=True):
@@ -926,51 +921,6 @@ def test_download_captures_description(client, monkeypatch):
assert result["item"]["source"]["title"] == "A clip"
-def _install_fake_ydl(monkeypatch, extract_info_fn, content_fn=None):
- """Patch a fake ``yt_dlp`` module. ``extract_info_fn(ydl, url, download)``
- returns the info dict from the (single) ``extract_info`` call; ``prepare_filename``
- writes a placeholder PNG next to the resolved name so ``download_url`` finds it
- — ``content_fn(info)`` picks its bytes (default: identical for every call;
- pass a per-``info`` variant to avoid sha256-dedup collisions across items
- that are supposed to be distinct, e.g. in a concurrency test).
- ``process_ie_result`` is a passthrough, matching the real "download from
- already-extracted info, no second extraction" call ``download_url`` makes."""
- import sys
- import types
-
- content_fn = content_fn or (lambda info: _png_bytes())
-
- class FakeYDL:
- def __init__(self, opts):
- self.opts = opts
-
- def __enter__(self):
- return self
-
- def __exit__(self, *exc):
- return False
-
- def prepare_filename(self, info):
- import os
-
- path = os.path.join(
- os.path.dirname(self.opts["outtmpl"]), f"{info['title']} [{info['id']}].png"
- )
- with open(path, "wb") as fh:
- fh.write(content_fn(info))
- return path
-
- def process_ie_result(self, info, download=True):
- return info
-
- def extract_info(self, url, download=False):
- return extract_info_fn(self, url, download)
-
- fake = types.ModuleType("yt_dlp")
- fake.YoutubeDL = FakeYDL
- monkeypatch.setitem(sys.modules, "yt_dlp", fake)
-
-
def test_download_reports_multi_without_downloading(client, monkeypatch):
"""A post with several attachments (e.g. a tweet with photos) comes back
from yt-dlp as a playlist with ``entries``. Without an ``index``,
@@ -994,7 +944,7 @@ def test_download_reports_multi_without_downloading(client, monkeypatch):
},
{"id": "p3", "title": None, "ext": "mp4"},
]
- _install_fake_ydl(
+ install_fake_ydl(
monkeypatch, lambda ydl, url, download: {"_type": "playlist", "entries": entries}
)
@@ -1055,7 +1005,7 @@ def test_download_with_index_picks_entry_and_keeps_custom_title(client, monkeypa
assert ydl.opts["playlist_items"] == "2"
return {"_type": "playlist", "entries": [entries[int(ydl.opts["playlist_items"]) - 1]]}
- _install_fake_ydl(monkeypatch, extract_info)
+ install_fake_ydl(monkeypatch, extract_info)
result = media_engine.download_url(
case, "https://x.com/user/status/123", index=2, title="My custom title"
@@ -1074,7 +1024,7 @@ def test_download_autofills_title_from_extraction(client, monkeypatch):
cid = client.post("/api/cases", json={"name": "AutoTitle"}).json()["id"]
case = Case.open(cid)
- _install_fake_ydl(
+ install_fake_ydl(
monkeypatch, lambda ydl, url, download: {"id": "abc123", "title": "Strike footage"}
)
@@ -1134,7 +1084,7 @@ class _FakeGalleryExtractor:
def request(self, url):
class Resp:
- content = _png_bytes()
+ content = png_bytes()
return Resp()
@@ -1470,7 +1420,7 @@ def test_download_reports_large_telegram_video_without_fallback(client, monkeypa
case = Case.open(cid)
url = "https://t.me/warhistoryalconafter/104333"
- _install_fake_ydl(monkeypatch, lambda ydl, target, download: None)
+ install_fake_ydl(monkeypatch, lambda ydl, target, download: None)
monkeypatch.setattr(media_engine, "_telegram_embed_media", lambda target: ([], True))
monkeypatch.setattr(
gdl_extractor,
@@ -1496,7 +1446,7 @@ def test_download_merges_telegram_video_and_photos(client, monkeypatch):
{"id": "v1", "title": "clip one", "ext": "mp4"},
{"id": "v2", "title": "clip two", "ext": "mp4"},
]
- _install_fake_ydl(
+ install_fake_ydl(
monkeypatch, lambda ydl, url, download: {"_type": "playlist", "entries": entries}
)
monkeypatch.setattr(
@@ -1529,7 +1479,7 @@ def test_download_picks_telegram_photo_from_mixed_post(client, monkeypatch):
{"id": "v1", "title": "clip one", "ext": "mp4"},
{"id": "v2", "title": "clip two", "ext": "mp4"},
]
- _install_fake_ydl(
+ install_fake_ydl(
monkeypatch, lambda ydl, url, download: {"_type": "playlist", "entries": entries}
)
monkeypatch.setattr(
@@ -1567,7 +1517,7 @@ def test_download_picks_yt_dlp_video_from_mixed_post(client, monkeypatch):
{"id": "v1", "title": "clip one", "ext": "mp4"},
{"id": "v2", "title": "clip two", "ext": "mp4"},
]
- _install_fake_ydl(
+ install_fake_ydl(
monkeypatch, lambda ydl, url, download: {"_type": "playlist", "entries": entries}
)
monkeypatch.setattr(
@@ -1604,10 +1554,10 @@ def test_concurrent_downloads_dont_lose_entities(client, monkeypatch):
# distinct bytes per item — identical content would legitimately dedup
# via sha256 and mask what this test is actually checking (entity loss,
# not the separate dedup-check race)
- _install_fake_ydl(
+ install_fake_ydl(
monkeypatch,
extract_info,
- content_fn=lambda info: _png_bytes(color=(int(info["id"][4:]), 0, 0)),
+ content_fn=lambda info: png_bytes(color=(int(info["id"][4:]), 0, 0)),
)
errors = []
@@ -1662,7 +1612,7 @@ def test_public_download_never_passes_cookies(client, monkeypatch):
assert "cookiefile" not in ydl.opts
return {"id": "abc123", "title": "Public clip"}
- _install_fake_ydl(monkeypatch, extract_info)
+ install_fake_ydl(monkeypatch, extract_info)
result = media_engine.download_url(case, "https://example.com/watch?v=abc123")
assert result["item"]["title"] == "Public clip"
@@ -1748,7 +1698,7 @@ def test_retry_with_browser_threads_cookiesfrombrowser(client, monkeypatch):
assert ydl.opts["cookiesfrombrowser"] == ("firefox",)
return {"id": "abc123", "title": "Gated clip"}
- _install_fake_ydl(monkeypatch, extract_info)
+ install_fake_ydl(monkeypatch, extract_info)
result = media_engine.download_url(
case, "https://youtube.com/watch?v=priv", cookies={"browser": "firefox"}
)
@@ -1769,7 +1719,7 @@ def test_windows_chromium_returns_guidance(client, monkeypatch):
monkeypatch.setattr(sys, "platform", "win32")
called = []
- _install_fake_ydl(monkeypatch, lambda ydl, url, download: called.append(1) or {"id": "x"})
+ install_fake_ydl(monkeypatch, lambda ydl, url, download: called.append(1) or {"id": "x"})
result = media_engine.download_url(
case, "https://youtube.com/watch?v=priv", cookies={"browser": "chrome"}
@@ -1794,7 +1744,7 @@ def test_cookies_file_threads_absolute_cookiefile(client, monkeypatch):
assert ydl.opts["cookiefile"] == str(config.cookies_file_path())
return {"id": "abc123", "title": "Gated via file"}
- _install_fake_ydl(monkeypatch, extract_info)
+ install_fake_ydl(monkeypatch, extract_info)
result = media_engine.download_url(
case, "https://youtube.com/watch?v=priv", cookies={"file": "cookies.txt"}
)
@@ -1936,7 +1886,7 @@ def test_concurrent_sidecar_merges_do_not_drop_each_other(client, monkeypatch):
monkeypatch.setattr(workqueue, "start_workers", False)
cid = client.post("/api/cases", json={"name": "Merge"}).json()["id"]
- rel = _upload(client, cid, "shot.png", _png_bytes()).json()["item"]["path"]
+ rel = _upload(client, cid, "shot.png", png_bytes()).json()["item"]["path"]
case = Case.open(cid)
start = threading.Barrier(2)
@@ -1981,7 +1931,7 @@ def test_naming_an_item_survives_the_enrichment_of_the_same_sidecar(client, monk
monkeypatch.setattr(workqueue, "start_workers", False)
cid = client.post("/api/cases", json={"name": "Naming"}).json()["id"]
- rel = _upload(client, cid, "shot.png", _png_bytes()).json()["item"]["path"]
+ rel = _upload(client, cid, "shot.png", png_bytes()).json()["item"]["path"]
case = Case.open(cid)
enrichment_started = threading.Event()
@@ -2033,9 +1983,9 @@ def test_media_page_filters_and_counts_the_files_that_state_a_position(client):
cid = client.post("/api/cases", json={"name": "Positions"}).json()["id"]
case = Case.open(cid)
- photo = _upload(client, cid, "photo.png", _png_bytes(color=(9, 0, 0))).json()["item"]
- clip = _upload(client, cid, "clip.png", _png_bytes(color=(10, 0, 0))).json()["item"]
- _upload(client, cid, "plain.png", _png_bytes(color=(11, 0, 0)))
+ photo = _upload(client, cid, "photo.png", png_bytes(color=(9, 0, 0))).json()["item"]
+ clip = _upload(client, cid, "clip.png", png_bytes(color=(10, 0, 0))).json()["item"]
+ _upload(client, cid, "plain.png", png_bytes(color=(11, 0, 0)))
media_engine.merge_item(case, photo["path"], {"gps": {"lat": 48.8583, "lon": 2.2945}})
# a video states its position in the container tags, not in EXIF
@@ -2071,7 +2021,7 @@ def test_media_page_ignores_a_half_written_position(client):
cid = client.post("/api/cases", json={"name": "Half position"}).json()["id"]
case = Case.open(cid)
- item = _upload(client, cid, "odd.png", _png_bytes(color=(12, 0, 0))).json()["item"]
+ item = _upload(client, cid, "odd.png", png_bytes(color=(12, 0, 0))).json()["item"]
for broken in ({"lat": 48.0}, {"lat": 48.0, "lon": None}, {"lat": "north", "lon": "east"}):
media_engine.merge_item(case, item["path"], {"gps": broken})
@@ -2089,7 +2039,7 @@ def test_the_browse_index_leaves_the_metadata_dumps_to_the_per_item_read(client)
cid = client.post("/api/cases", json={"name": "Fat metadata"}).json()["id"]
case = Case.open(cid)
- item = _upload(client, cid, "shot.png", _png_bytes()).json()["item"]
+ item = _upload(client, cid, "shot.png", png_bytes()).json()["item"]
exif = {f"Tag{n:03d}": "v" * 64 for n in range(120)}
media_engine.merge_item(case, item["path"], {"exif": exif, "gps": {"lat": 1.0, "lon": 2.0}})
@@ -2129,7 +2079,7 @@ def test_enrich_counts_the_jobs_the_queue_took(client):
from azimut.engine import workqueue
cid = client.post("/api/cases", json={"name": "Enrich count"}).json()["id"]
- image = _upload(client, cid, "shot.png", _png_bytes()).json()["item"]
+ image = _upload(client, cid, "shot.png", png_bytes()).json()["item"]
audio = client.post(
f"/api/cases/{cid}/media/upload",
files={"file": ("note.mp3", io.BytesIO(b"ID3\x04\x00\x00\x00\x00\x00\x00"), "audio/mpeg")},
@@ -2155,7 +2105,7 @@ def test_enrich_counts_the_jobs_the_queue_took(client):
def _paste(client, cid, data=None, name="image.png", **fields):
return client.post(
f"/api/cases/{cid}/media/paste",
- files={"file": (name, io.BytesIO(_png_bytes() if data is None else data), "image/png")},
+ files={"file": (name, io.BytesIO(png_bytes() if data is None else data), "image/png")},
data=fields,
)
@@ -2202,7 +2152,7 @@ def test_pasting_the_same_crop_twice_is_one_file(client):
"""Deduped like any import: the bytes are the identity, whatever gesture
brought them in, and a second Ctrl+V is usually a doubt about the first."""
cid = client.post("/api/cases", json={"name": "Twice"}).json()["id"]
- pixels = _png_bytes(color=(3, 9, 27))
+ pixels = png_bytes(color=(3, 9, 27))
first = _paste(client, cid, pixels, title="Gate").json()
again = _paste(client, cid, pixels, title="Gate again").json()
@@ -2216,8 +2166,8 @@ def test_a_paste_and_a_drop_count_as_one_facet(client):
Imports filter asks. They stay two source types because only one of them can
say where it came from."""
cid = client.post("/api/cases", json={"name": "Facet"}).json()["id"]
- _upload(client, cid, "dropped.png", _png_bytes(color=(1, 2, 3)))
- _paste(client, cid, _png_bytes(color=(4, 5, 6)), title="Pasted")
+ _upload(client, cid, "dropped.png", png_bytes(color=(1, 2, 3)))
+ _paste(client, cid, png_bytes(color=(4, 5, 6)), title="Pasted")
facets = client.get(f"/api/cases/{cid}/media/page").json()["facets"]
assert facets["category_counts"]["upload"] == 2
@@ -2305,14 +2255,14 @@ def test_a_slot_that_needs_a_picture_is_not_handed_the_quoted_video(client, monk
cid = client.post("/api/cases", json={"name": "QuotedVideo"}).json()["id"]
case = Case.open(cid)
- _install_fake_ydl(
+ install_fake_ydl(
monkeypatch,
lambda ydl, url, download=False: {
"id": "v1", "title": "the quoted clip", "ext": "mp4", "extractor": "twitter",
},
# Distinct bytes from the picture below, or the library would dedupe the two and
# the test would be reading the first download back twice.
- content_fn=lambda info: _png_bytes(color=(10, 90, 200)),
+ content_fn=lambda info: png_bytes(color=(10, 90, 200)),
)
monkeypatch.setattr(
gdl_extractor,
diff --git a/tests/test_proof_import.py b/tests/test_proof_import.py
index 54cba3e..85ef740 100644
--- a/tests/test_proof_import.py
+++ b/tests/test_proof_import.py
@@ -13,6 +13,7 @@ Three promises are what these tests hold to:
import io
+from fakeydl import install_fake_ydl
from jobwait import job_result
from PIL import Image
@@ -246,9 +247,7 @@ def test_the_fetch_holds_the_download_and_reads_the_post(client, monkeypatch):
"""The one path the hand-attached tests cannot reach: a real download, with
the extractor faked. The file must land in staging and nowhere else, and the
post's text must come back scanned."""
- from test_media_api import _install_fake_ydl
-
- _install_fake_ydl(
+ install_fake_ydl(
monkeypatch,
lambda ydl, url, download: {
"id": "p1",
diff --git a/tests/test_radar_detect.py b/tests/test_radar_detect.py
index 80e17f4..b562d16 100644
--- a/tests/test_radar_detect.py
+++ b/tests/test_radar_detect.py
@@ -16,16 +16,9 @@ from azimut import config
from azimut.engine import analyzers, sentinel, tilecache, workqueue
from azimut.engine.analysis_models import BUILTINS, RunInput, Source
from azimut.workspace import Case
-from analyzerfixture import EDGE, PAD, SENTINEL_TILE, zone
+from analyzerfixture import EDGE, PAD, SAR_LAYER, SAR_TIME, SENTINEL_TILE, sar_level, zone
-LAYER = "SAR_IW"
DAY_A, DAY_B = "2026-05-02", "2026-05-14"
-TIME = "05:42:10"
-
-
-def level(db):
- return np.clip(np.round((np.asarray(db, float) - sentinel.SAR_DB_FLOOR) / sentinel.SAR_DB_STEP),
- 1, 255).astype(np.uint8)
def speckled(mean_db, seed, size=EDGE, looks=4.4):
@@ -50,8 +43,8 @@ def recipe(rid, **parameters):
def body(rid, **parameters):
return RunInput.model_validate({
"title": rid, "zones": [zone()], "recipe": recipe(rid, **parameters).model_dump(),
- "a": {"provider": "sentinel1", "date": DAY_A, "layer": LAYER, "maxcc": 100, "time": TIME},
- "b": {"provider": "sentinel1", "date": DAY_B, "layer": LAYER, "maxcc": 100, "time": TIME},
+ "a": {"provider": "sentinel1", "date": DAY_A, "layer": SAR_LAYER, "maxcc": 100, "time": SAR_TIME},
+ "b": {"provider": "sentinel1", "date": DAY_B, "layer": SAR_LAYER, "maxcc": 100, "time": SAR_TIME},
"offline": True,
})
@@ -80,8 +73,8 @@ def test_radar_products_carry_decibels_in_fifths_and_are_never_zero_where_seen()
picture = base64.b64decode(sentinel._evalscript("sar-picture")).decode("ascii")
assert "stretch(db(p.VV) - db(p.VH)" in picture
# the byte goes back to decibels exactly on the grid it was rounded to
- assert sentinel.sar_decibels(level(-22.0).astype(float)) == pytest.approx(-22.0)
- assert sentinel.sar_decibels(level(3.4).astype(float)) == pytest.approx(3.4)
+ assert sentinel.sar_decibels(sar_level(-22.0).astype(float)) == pytest.approx(-22.0)
+ assert sentinel.sar_decibels(sar_level(3.4).astype(float)) == pytest.approx(3.4)
def test_a_pass_window_holds_one_pass_and_crosses_midnight():
@@ -115,10 +108,10 @@ def test_band_frame_reads_the_pass_and_the_water_reads_the_clearest_year(monkeyp
return Answer((int(params["WIDTH"]), int(params["HEIGHT"])))
box = (0.0, 0.0, 1000.0, 1000.0)
- sentinel.band_frame("inst", box, 8, 8, "2026-05-14", "sar", 100, layer=LAYER, time=TIME, get=get)
+ sentinel.band_frame("inst", box, 8, 8, "2026-05-14", "sar", 100, layer=SAR_LAYER, time=SAR_TIME, get=get)
sentinel.band_frame("inst", box, 8, 8, "2026-05-01", "water", 100, get=get)
radar_request, water_request = sent
- assert radar_request["LAYERS"] == LAYER
+ assert radar_request["LAYERS"] == SAR_LAYER
assert radar_request["TIME"] == "2026-05-14T05:22:10Z/2026-05-14T06:02:10Z"
assert water_request["LAYERS"] == "TRUE_COLOR"
assert water_request["TIME"] == "2025-05-01/2026-05-01"
@@ -216,7 +209,7 @@ def test_the_sentinel1_probe_tells_a_radar_layer_from_an_optical_one():
def raise_for_status(self):
return None
- assert sentinel.probe_sar_layer("inst", LAYER, get=lambda *a, **k: Rendered())["ok"]
+ assert sentinel.probe_sar_layer("inst", SAR_LAYER, get=lambda *a, **k: Rendered())["ok"]
with pytest.raises(ValueError):
sentinel.probe_sar_layer("inst", "../etc", get=lambda *a, **k: Rendered())
@@ -230,7 +223,7 @@ def _sea_with(targets, seed=1, sea_vv=-22.0, sea_vh=-28.0):
vv[y:y + h, x:x + w] = target_vv
vh[y:y + h, x:x + w] = target_vh
product = np.zeros((EDGE, EDGE, 4), np.uint8)
- product[..., 0], product[..., 1], product[..., 3] = level(vv), level(vh), 255
+ product[..., 0], product[..., 1], product[..., 3] = sar_level(vv), sar_level(vh), 255
return product
@@ -302,7 +295,7 @@ def test_radar_change_gates_bright_loss_bright_gain_and_new_water():
vv[field] += field_db[0] + 10
vh[field] += field_db[1] + 16
product = np.zeros((EDGE, EDGE, 4), np.uint8)
- product[..., 0], product[..., 1], product[..., 3] = level(vv), level(vh), 255
+ product[..., 0], product[..., 1], product[..., 3] = sar_level(vv), sar_level(vh), 255
return product
standing = scene(town_db=(0.0, -8.0))
@@ -344,7 +337,7 @@ def test_ground_that_did_not_change_stays_quiet_between_two_passes():
def scene(seed, vv_db, vh_db):
product = np.zeros((EDGE, EDGE, 4), np.uint8)
- product[..., 0], product[..., 1] = level(correlated(vv_db, seed)), level(correlated(vh_db, seed + 100))
+ product[..., 0], product[..., 1] = sar_level(correlated(vv_db, seed)), sar_level(correlated(vh_db, seed + 100))
product[..., 3] = 255
return product
@@ -370,7 +363,7 @@ def test_every_radar_built_in_names_its_method_and_the_old_ones_stay():
def radar_case(client, monkeypatch):
monkeypatch.setattr(workqueue, "start_workers", False)
ident = client.post("/api/cases", json={"name": "Radar tests"}).json()["id"]
- client.put("/api/settings/prefs", json={"sentinel1_layer": LAYER})
+ client.put("/api/settings/prefs", json={"sentinel1_layer": SAR_LAYER})
def forbidden(*args, **kwargs):
raise AssertionError("unexpected network")
@@ -413,14 +406,14 @@ def test_an_offline_radar_sweep_reads_the_pass_it_names_and_keeps_its_water(clie
for letter in "ab":
payload[letter] = {**payload[letter], "provider": "sentinel2", "layer": "TRUE_COLOR", "maxcc": 30}
sea = _sea_with([((300, 300, 8, 3), (5.0, -8.0))])
- _seed({"provider": "sentinel1", "date": DAY_B, "layer": LAYER, "maxcc": 100, "time": TIME},
+ _seed({"provider": "sentinel1", "date": DAY_B, "layer": SAR_LAYER, "maxcc": 100, "time": SAR_TIME},
sea, water(sentinel.WATER_WATER))
saved = _run(client, case, payload)
assert saved["status"] == "ready", saved
assert saved["count"] == 1
row = saved["results"][0]
- assert row["sources"]["b"] == {"provider": "sentinel1", "date": DAY_B, "layer": LAYER,
- "maxcc": 100, "time": TIME}
+ assert row["sources"]["b"] == {"provider": "sentinel1", "date": DAY_B, "layer": SAR_LAYER,
+ "maxcc": 100, "time": SAR_TIME}
assert "dB" not in row["measure"] and row["measure"]["value"] > 9
# the water it was judged against is kept beside the picture and the product
assert sorted(frame["index"] or "picture" for frame in saved["frames"].values()) == [
@@ -449,7 +442,7 @@ def test_a_typed_day_is_pinned_to_the_pass_on_the_other_sides_track(client, rada
monkeypatch.setattr(analyzers.sentinel, "acquisitions", acquisitions)
client.put("/api/settings/keys", json={"sentinelhub": "test-instance"})
- client.put("/api/settings/prefs", json={"sentinel1_layer": LAYER})
+ client.put("/api/settings/prefs", json={"sentinel1_layer": SAR_LAYER})
typed = body("radar-change").model_copy(update={"offline": False})
typed = typed.model_copy(update={"b": typed.b.model_copy(update={"time": ""})})
settled = analyzers.resolve_dates(radar_case, typed)
@@ -467,12 +460,12 @@ def test_an_automatic_radar_pass_stays_on_the_reference_track(client, radar_case
{"date": "2026-05-30", "time": "05:42:30", "cloud": None, "coverage": 1.0},
]})
client.put("/api/settings/keys", json={"sentinelhub": "test-instance"})
- client.put("/api/settings/prefs", json={"sentinel1_layer": LAYER})
+ client.put("/api/settings/prefs", json={"sentinel1_layer": SAR_LAYER})
routine = body("radar-razed").model_copy(update={"offline": False, "date_rule": "latest_reference"})
routine = routine.model_copy(update={"b": routine.b.model_copy(update={"date": "", "time": ""})})
settled = analyzers.resolve_dates(radar_case, routine)
assert (settled.b.date, settled.b.time) == ("2026-05-30", "05:42:30")
- assert settled.a.time == TIME
+ assert settled.a.time == SAR_TIME
def test_optical_sources_dump_as_they_always_did():
@@ -480,7 +473,7 @@ def test_optical_sources_dump_as_they_always_did():
not grow a field because radar sources carry a time."""
optical = Source(date=DAY_B)
assert "time" not in optical.model_dump()
- assert Source(provider="sentinel1", date=DAY_B, layer=LAYER, time=TIME).model_dump()["time"] == TIME
+ assert Source(provider="sentinel1", date=DAY_B, layer=SAR_LAYER, time=SAR_TIME).model_dump()["time"] == SAR_TIME
old = deepcopy(optical.model_dump())
assert analyzers._key(Source.model_validate(old), 13, 1, 2, None) == \
analyzers._key(optical, 13, 1, 2, None)
@@ -496,19 +489,19 @@ def test_finding_the_radar_layer_skips_template_layers_and_keeps_the_first_that_
probed = []
monkeypatch.setattr(satellite.sentinel, "serves_sentinel1", lambda instance: True)
monkeypatch.setattr(satellite.sentinel, "capabilities_layers", lambda instance: [
- {"id": "TRUE_COLOR"}, {"id": "SWIR"}, {"id": "MY_NOTES"}, {"id": LAYER}, {"id": "LATER"}])
+ {"id": "TRUE_COLOR"}, {"id": "SWIR"}, {"id": "MY_NOTES"}, {"id": SAR_LAYER}, {"id": "LATER"}])
def probe(instance, layer):
probed.append(layer)
- return {"ok": layer == LAYER, "layer": layer, "detail": "reads Sentinel-1 VV and VH"}
+ return {"ok": layer == SAR_LAYER, "layer": layer, "detail": "reads Sentinel-1 VV and VH"}
monkeypatch.setattr(satellite.sentinel, "probe_sar_layer", probe)
before = config.month_usage("sentinelhub")
answer = client.post("/api/satellite/sentinel1/layer", json={}).json()
- assert answer["ok"] and answer["layer"] == LAYER
- assert probed == ["MY_NOTES", LAYER]
+ assert answer["ok"] and answer["layer"] == SAR_LAYER
+ assert probed == ["MY_NOTES", SAR_LAYER]
assert config.month_usage("sentinelhub") == before + 2
- assert client.get("/api/settings").json()["sentinel1_layer"] == LAYER
+ assert client.get("/api/settings").json()["sentinel1_layer"] == SAR_LAYER
# a new instance is another configuration: its radar layer is found again
client.put("/api/settings/keys", json={"sentinelhub": "other-instance"})
assert client.get("/api/settings").json()["sentinel1_layer"] == ""
@@ -530,7 +523,7 @@ def test_an_instance_without_sentinel1_is_told_before_any_probe(client, monkeypa
# -- the radar basemap ----------------------------------------------------------------------
-def _radar_settings(monkeypatch, tmp_path, layer=LAYER):
+def _radar_settings(monkeypatch, tmp_path, layer=SAR_LAYER):
from azimut.engine import tiles
monkeypatch.setenv("AZIMUT_HOME", str(tmp_path))
@@ -544,7 +537,7 @@ def test_the_radar_basemap_is_offered_once_its_layer_is_known(monkeypatch, tmp_p
assert "sentinel1" not in {p.id for p in tiles.all_providers()}
tiles = _radar_settings(monkeypatch, tmp_path)
radar_map = next(p for p in tiles.all_providers() if p.id == "sentinel1")
- assert f"LAYER={LAYER}" in radar_map.url and "inst-uuid" in radar_map.url
+ assert f"LAYER={SAR_LAYER}" in radar_map.url and "inst-uuid" in radar_map.url
assert "EVALSCRIPT=" in radar_map.url and "TIME=" not in radar_map.url
# the same quota and the same native ceiling as the optical basemap
assert (radar_map.meter, radar_map.tile_size, radar_map.max_native_zoom) == ("sentinelhub", 512, 14)
@@ -579,26 +572,26 @@ def test_radar_difference_needs_two_passes_of_one_track(client):
def test_a_radar_comparison_saves_its_passes(client):
client.put("/api/settings/keys", json={"sentinelhub": "inst-uuid"})
- client.put("/api/settings/prefs", json={"sentinel1_layer": LAYER})
+ client.put("/api/settings/prefs", json={"sentinel1_layer": SAR_LAYER})
cid = client.post("/api/cases", json={"name": "Radar compare"}).json()["id"]
side = {"present": True, "provider": "sentinel1", "overlays": [],
"sentinel": {"layer": "TRUE_COLOR", "date": "", "maxcc": 100}, "wayback_release": None}
spec = {"version": 2, "camera": {"lat": 51.9, "lon": 4.0, "zoom": 13}, "mode": "side",
- "a": {**side, "radar": {"date": DAY_A, "time": TIME}},
- "b": {**side, "radar": {"date": DAY_B, "time": TIME}}}
+ "a": {**side, "radar": {"date": DAY_A, "time": SAR_TIME}},
+ "b": {**side, "radar": {"date": DAY_B, "time": SAR_TIME}}}
saved = client.post(f"/api/cases/{cid}/compare/sessions", json={"title": "Radar pair", "spec": spec})
assert saved.status_code == 200, saved.text
reopened = client.get(f"/api/cases/{cid}/compare/sessions/{saved.json()['name']}").json()
- assert (reopened.get("spec") or reopened)["b"]["radar"] == {"date": DAY_B, "time": TIME}
+ assert (reopened.get("spec") or reopened)["b"]["radar"] == {"date": DAY_B, "time": SAR_TIME}
def test_the_radar_layer_travels_with_the_backup(client):
- client.put("/api/settings/prefs", json={"sentinel1_layer": LAYER})
+ client.put("/api/settings/prefs", json={"sentinel1_layer": SAR_LAYER})
bundle = client.get("/api/settings/export").json()
- assert bundle["settings"]["sentinel1_layer"] == LAYER
+ assert bundle["settings"]["sentinel1_layer"] == SAR_LAYER
client.put("/api/settings/prefs", json={"sentinel1_layer": ""})
assert client.post("/api/settings/import", json=bundle).status_code == 200
- assert client.get("/api/settings").json()["sentinel1_layer"] == LAYER
+ assert client.get("/api/settings").json()["sentinel1_layer"] == SAR_LAYER
bad = {**bundle, "settings": {**bundle["settings"], "sentinel1_layer": "../x"}}
assert client.post("/api/settings/import", json=bad).status_code == 422
@@ -609,9 +602,9 @@ def test_a_radar_routine_stays_on_the_track_it_has_run_on(client, radar_case, mo
and read the change in angle as change on the ground."""
case = radar_case
client.put("/api/settings/keys", json={"sentinelhub": "test-instance"})
- client.put("/api/settings/prefs", json={"sentinel1_layer": LAYER})
+ client.put("/api/settings/prefs", json={"sentinel1_layer": SAR_LAYER})
monkeypatch.setattr(analyzers, "previous_pass", lambda case, body: Source(
- provider="sentinel1", date=DAY_B, layer=LAYER, maxcc=100, time="05:42:10"))
+ provider="sentinel1", date=DAY_B, layer=SAR_LAYER, maxcc=100, time="05:42:10"))
monkeypatch.setattr(analyzers.sentinel, "acquisitions", lambda *a, **k: {"dates": [
{"date": "2026-05-28", "time": "17:33:02", "cloud": None, "coverage": 1.0},
{"date": "2026-05-26", "time": "05:42:30", "cloud": None, "coverage": 1.0},
diff --git a/tests/test_stitch.py b/tests/test_stitch.py
index dd4042f..2130db1 100644
--- a/tests/test_stitch.py
+++ b/tests/test_stitch.py
@@ -3,59 +3,15 @@
The solvers are exercised against synthetic scenes, so the right answer is known
up front. Planar gets a scene cut into overlapping crops: the crops' offset is
what we asked for, and the solved quads must reproduce it. The rotation model gets
-views rendered through a camera turned by known angles — built here by direct
-sampling, so nothing under test is used to make its own input.
+views rendered through a camera turned by known angles — built by direct sampling
+in `stitchscene.py`, so nothing under test is used to make its own input.
"""
-import math
-import random
-
import pytest
-from PIL import Image, ImageDraw
+from PIL import Image
from azimut.engine import stitch
-
-
-def _scene(width=900, height=500, seed=7, blobs=220) -> Image.Image:
- """A richly textured scene — random blobs give the detector real features."""
- rng = random.Random(seed)
- img = Image.new("RGB", (width, height), (18, 20, 28))
- draw = ImageDraw.Draw(img)
- for _ in range(blobs):
- x, y = rng.randrange(width), rng.randrange(height)
- r = rng.randrange(6, 34)
- color = (rng.randrange(40, 255), rng.randrange(40, 255), rng.randrange(40, 255))
- if rng.random() < 0.5:
- draw.ellipse([x, y, x + r, y + r], fill=color)
- else:
- draw.rectangle([x, y, x + r, y + int(r * 0.7)], fill=color)
- return img
-
-
-def _pan(angles, width=520, height=420, focal=520.0, seed=5) -> list[Image.Image]:
- """Views of one world through a pinhole camera yawed by each of ``angles``.
-
- The world is a 360°-wide cylindrical scene; each view samples it through the
- camera's rays, which is exactly the situation the planar model cannot express
- and the rotation model can.
- """
- import cv2
- import numpy as np
-
- world = np.asarray(_scene(4000, 900, seed=seed, blobs=3000))
- wh, ww = world.shape[:2]
- world_focal = ww / (2 * math.pi)
-
- out = []
- ys, xs = np.mgrid[0:height, 0:width].astype(np.float32)
- for deg in angles:
- x = (xs - width / 2) / focal
- y = (ys - height / 2) / focal
- theta = np.arctan2(x, np.ones_like(x)) + math.radians(deg)
- map_x = ((theta * world_focal) % ww).astype(np.float32)
- map_y = ((y / np.sqrt(x**2 + 1)) * world_focal + wh / 2).astype(np.float32)
- out.append(Image.fromarray(cv2.remap(world, map_x, map_y, cv2.INTER_LINEAR)))
- return out
+from stitchscene import _pan, _scene
def _overlaid(images, box=(18, 18, 138, 88), seed=41) -> list[Image.Image]: