fuzzyworld

fuzzyworld-tools / files / tests / test_blog_watch.py

test_blog_watch.py

48.7 KB · history · blame

1"""Tests for server/blog_watch.py (`fw blog watch`). Run: python3 -m unittest discover tests
2
3Every blog, repo and state folder here is made up, in a temporary folder. Git and rsync are real (local bare
4repo as the "remote"); the clock, notifications and deploy are fakes. Nothing touches the network or ~/Library.
5"""
6import io
7import json
8import os
9import plistlib
10import shutil
11import subprocess
12import sys
13import tempfile
14import unittest
15from unittest import mock
16
17sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "server"))
18import blog # noqa: E402
19import blog_watch as bw # noqa: E402
20
21# No real macOS notifications from a test run (some tests go through the default notifier).
22os.environ["FW_BLOG_WATCH_NOTIFY"] = "0"
23
24needs_markdown = unittest.skipUnless(blog.markdown, "Python-Markdown is not installed (see FW_PYLIB)")
25
26
27class Clock:
28 def __init__(self, t=1_800_000_000.0):
29 self.t = t
30
31 def __call__(self):
32 return self.t
33
34 def advance(self, seconds):
35 self.t += seconds
36
37
38def git(repo, *args):
39 return subprocess.run(["git", "-C", repo, *args], capture_output=True, text=True, check=True).stdout
40
41
42class WatchCase(unittest.TestCase):
43 """A made-up blog folder `MyBlog/` (config + src/), a state dir, a fake clock and notifier."""
44
45 def setUp(self):
46 self.dir = tempfile.mkdtemp()
47 self.addCleanup(shutil.rmtree, self.dir, ignore_errors=True)
48 self.root = os.path.join(self.dir, "MyBlog")
49 self.src = os.path.join(self.root, "src")
50 self.sd = os.path.join(self.dir, "state")
51 os.makedirs(self.src)
52 gitconfig = os.path.join(self.dir, "gitconfig")
53 with open(gitconfig, "w") as f:
54 f.write("[user]\n\tname = Test Writer\n\temail = test@example.org\n[init]\n\tdefaultBranch = main\n")
55 self.gitconfig = gitconfig
56 saved = {k: os.environ.get(k) for k in ("FW_BLOG_WATCH_DIR", "GIT_CONFIG_GLOBAL", "GIT_CONFIG_NOSYSTEM")}
57 os.environ.update(FW_BLOG_WATCH_DIR=self.sd, GIT_CONFIG_GLOBAL=gitconfig, GIT_CONFIG_NOSYSTEM="1")
58 self.addCleanup(lambda: [os.environ.pop(k, None) if v is None else os.environ.__setitem__(k, v)
59 for k, v in saved.items()])
60 self.clock = Clock()
61 self.notes = []
62 self.deploys = []
63 self.built = {"index.html": "<p>home</p>", "a/index.html": "<p>a</p>"}
64 self.config = {"title": "T", "base_url": "https://blog.example.org", "source": "src",
65 "deploy": {"host": "dh", "dir": "writing.example.org"}}
66 self.write("one.md", "# One\n\nbody\n")
67
68 def write(self, rel, text, base=None):
69 path = os.path.join(base or self.src, rel)
70 os.makedirs(os.path.dirname(path), exist_ok=True)
71 with open(path, "w", encoding="utf-8") as f:
72 f.write(text)
73
74 def cfg_path(self, **extra):
75 self.config.update(extra)
76 path = os.path.join(self.root, "fw-blog.json")
77 with open(path, "w") as f:
78 json.dump(self.config, f)
79 self.cfg_file = path
80 return path
81
82 def fake_build(self, cfg, out):
83 for rel, text in self.built.items():
84 self.write(rel, text, base=out)
85
86 def fake_deploy(self, cfg, out):
87 self.deploys.append(sorted(os.listdir(out)))
88
89 def env(self, **kw):
90 kw.setdefault("build", self.fake_build)
91 kw.setdefault("deploy", self.fake_deploy)
92 return bw.Env(now=self.clock, notify=self.notes.append, **kw)
93
94 def tick(self, path, **kw):
95 return bw.tick(path, self.env(**kw))
96
97 def settle(self, path, seconds=301, **kw):
98 """The first tick sees a change; after the quiet period the next one acts."""
99 self.assertEqual(self.tick(path, **kw), "changed")
100 self.clock.advance(seconds)
101 return self.tick(path, **kw)
102
103 def log(self):
104 with open(os.path.join(self.sd, "watch.log")) as f:
105 return f.read()
106
107 def state(self):
108 with open(os.path.join(self.sd, "state.json")) as f:
109 return json.load(f)
110
111 def baseline(self, files=None, **kw):
112 """deployed.json as a manual deploy of the current config and code would have left it."""
113 blog.write_deployed(self.sd, files if files is not None else
114 {rel: __import__("hashlib").sha256(t.encode()).hexdigest() for rel, t in self.built.items()},
115 cfg=kw.pop("cfg", None) or blog.load_config(self.cfg_file), **kw)
116
117
118class Fingerprint(WatchCase):
119 def test_ignores_junk(self):
120 before, conflicts = bw.scan(self.src)
121 self.write(".DS_Store", "x")
122 self.write(".dropbox", "x")
123 self.write(".dropbox.cache/a", "x")
124 self.write(".git/config", "x")
125 self.write("sub/.git/HEAD", "x")
126 self.write("one (conflicted copy 2026-11-02).md", "x")
127 after, conflicts = bw.scan(self.src)
128 self.assertEqual(before, after)
129 self.assertEqual(conflicts, ["one (conflicted copy 2026-11-02).md"])
130
131 def test_content_and_name_change_it(self):
132 a, _ = bw.scan(self.src)
133 self.write("one.md", "# One\n\nbody!\n")
134 b, _ = bw.scan(self.src)
135 os.rename(os.path.join(self.src, "one.md"), os.path.join(self.src, "two.md"))
136 c, _ = bw.scan(self.src)
137 self.assertEqual(len({a, b, c}), 3)
138
139 def test_symlinks_are_not_followed(self):
140 outside = os.path.join(self.dir, "outside")
141 os.makedirs(outside)
142 self.write("x.txt", "1", base=outside)
143 os.symlink(outside, os.path.join(self.src, "link"))
144 a, _ = bw.scan(self.src)
145 self.write("x.txt", "2", base=outside)
146 b, _ = bw.scan(self.src)
147 self.assertEqual(a, b)
148
149
150class Quiet(WatchCase):
151 def test_waits_for_quiet_period_then_acts(self):
152 path = self.cfg_path(autodeploy={})
153 self.assertEqual(self.tick(path), "changed")
154 self.clock.advance(100)
155 self.assertEqual(self.tick(path), "waiting")
156 self.assertEqual(self.tick(path), "waiting")
157 self.assertEqual(self.log().count("waiting"), 1) # logged once per change
158 self.clock.advance(201)
159 self.assertEqual(self.tick(path), "held") # no baseline
160 self.assertTrue(self.state()["handled"])
161 self.assertEqual(self.tick(path), "idle")
162
163 def test_change_during_wait_resets_the_timer(self):
164 path = self.cfg_path(autodeploy={"quiet_seconds": 120})
165 self.tick(path)
166 self.clock.advance(100)
167 self.write("one.md", "# One\n\nmore\n")
168 self.assertEqual(self.tick(path), "changed")
169 self.clock.advance(100)
170 self.assertEqual(self.tick(path), "waiting")
171 self.clock.advance(21)
172 self.assertEqual(self.tick(path), "held")
173
174 def test_conflict_file_blocks_and_notifies_once(self):
175 path = self.cfg_path(autodeploy={})
176 self.baseline()
177 self.write("one (conflicted copy).md", "x")
178 self.assertEqual(self.settle(path), "conflict")
179 self.assertFalse(self.state()["handled"])
180 self.clock.advance(60)
181 self.assertEqual(self.tick(path), "conflict")
182 self.assertEqual(len(self.notes), 1)
183 self.assertEqual(self.deploys, [])
184 os.remove(os.path.join(self.src, "one (conflicted copy).md"))
185 self.assertEqual(self.tick(path), "changed") # resolved: the timer starts over
186
187 def test_nothing_configured(self):
188 self.assertEqual(self.tick(self.cfg_path()), "noop")
189
190 def test_config_error_notifies_once(self):
191 path = self.cfg_path(autodeploy={"quiet_seconds": 5})
192 self.assertEqual(self.tick(path), "config-error")
193 self.assertEqual(self.tick(path), "config-error")
194 self.assertEqual(len(self.notes), 1)
195
196
197class Lock(WatchCase):
198 def test_second_instance_exits_quietly(self):
199 path = self.cfg_path(autodeploy={})
200 os.makedirs(self.sd)
201 with open(os.path.join(self.sd, "lock"), "a") as held:
202 import fcntl
203 fcntl.flock(held, fcntl.LOCK_EX | fcntl.LOCK_NB)
204 self.assertEqual(self.tick(path), "locked")
205 self.assertFalse(os.path.exists(os.path.join(self.sd, "state.json")))
206 self.assertEqual(self.tick(path), "changed") # released: works again
207
208
209class Mirror(WatchCase):
210 def setUp(self):
211 super().setUp()
212 self.repo = os.path.join(self.dir, "repo")
213 self.path = self.cfg_path(mirror={"repo": self.repo})
214
215 def commits(self):
216 return git(self.repo, "log", "--format=%s").splitlines()
217
218 def test_first_run_inits_and_commits(self):
219 self.write("img/a.png", "png")
220 self.write(".DS_Store", "x")
221 self.assertEqual(self.settle(self.path), "mirrored")
222 self.assertEqual(git(self.repo, "symbolic-ref", "--short", "HEAD").strip(), "dropbox-mirror")
223 self.assertEqual(sorted(git(self.repo, "ls-files").split()), ["img/a.png", "one.md"])
224 self.assertRegex(self.commits()[0], r"^Mirror of src at \d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ$")
225 self.assertEqual(git(self.repo, "log", "-1", "--format=%an <%ae>").strip(), "Test Writer <test@example.org>")
226 self.assertEqual(git(self.repo, "log", "-1", "--format=%b").strip(), "")
227 self.assertEqual(self.notes, [])
228
229 def test_empty_existing_folder_is_initialised(self):
230 os.makedirs(self.repo)
231 self.assertEqual(self.settle(self.path), "mirrored")
232 self.assertEqual(len(self.commits()), 1)
233
234 def test_no_change_makes_no_commit_and_edit_and_delete_do(self):
235 self.settle(self.path)
236 self.write("one.md", "# One\n\nsame fingerprint? no, changed\n")
237 self.assertEqual(self.settle(self.path), "mirrored")
238 self.assertEqual(len(self.commits()), 2)
239 os.remove(os.path.join(self.src, "one.md"))
240 self.write("two.md", "x")
241 self.assertEqual(self.settle(self.path), "mirrored")
242 self.assertEqual(git(self.repo, "ls-files").split(), ["two.md"]) # deleted file is deleted in the repo
243 self.assertEqual(len(self.commits()), 3)
244 # a junk-only change alters nothing: not even a tick's worth of work
245 self.write(".DS_Store", "x")
246 self.assertEqual(self.tick(self.path), "idle")
247
248 def test_noop_when_content_is_the_same(self):
249 self.settle(self.path)
250 # force another pass without a source change: no commit
251 state = self.state()
252 state["handled"] = False
253 with open(os.path.join(self.sd, "state.json"), "w") as f:
254 json.dump(state, f)
255 self.clock.advance(400)
256 self.assertEqual(self.tick(self.path), "mirrored")
257 self.assertEqual(len(self.commits()), 1)
258
259 def test_dirty_tree_is_refused(self):
260 self.settle(self.path)
261 self.write("scratch.txt", "mine", base=self.repo)
262 self.write("one.md", "# One\n\nedited\n")
263 self.assertEqual(self.settle(self.path), "blocked")
264 self.assertTrue(os.path.exists(os.path.join(self.repo, "scratch.txt"))) # never overwritten or deleted
265 self.assertEqual(len(self.commits()), 1)
266 self.assertFalse(self.state()["handled"])
267 self.assertEqual(len(self.notes), 1)
268 self.assertIn("uncommitted", self.notes[0])
269 self.clock.advance(60)
270 self.tick(self.path)
271 self.assertEqual(len(self.notes), 1) # once
272
273 def test_wrong_branch_is_refused(self):
274 self.settle(self.path)
275 git(self.repo, "checkout", "-q", "-b", "other")
276 self.write("one.md", "# One\n\nedited\n")
277 self.assertEqual(self.settle(self.path), "blocked")
278 self.assertIn("other", self.notes[0])
279 self.assertEqual(git(self.repo, "log", "--format=%s", "other").count("Mirror"), 1)
280
281 def test_non_git_folder_is_refused(self):
282 self.write("something", "x", base=self.repo)
283 self.assertEqual(self.settle(self.path), "blocked")
284 self.assertIn("not a git repository", self.notes[0])
285 self.assertFalse(os.path.exists(os.path.join(self.repo, ".git")))
286
287 def test_in_progress_merge_is_refused(self):
288 self.settle(self.path)
289 gitdir = git(self.repo, "rev-parse", "--absolute-git-dir").strip()
290 with open(os.path.join(gitdir, "MERGE_HEAD"), "w") as f:
291 f.write(git(self.repo, "rev-parse", "HEAD"))
292 self.write("one.md", "# One\n\nedited\n")
293 self.assertEqual(self.settle(self.path), "blocked")
294 self.assertIn("MERGE_HEAD", self.notes[0])
295
296 def test_missing_git_identity_fails_clearly(self):
297 open(self.gitconfig, "w").close()
298 self.assertEqual(self.settle(self.path), "blocked")
299 self.assertIn("user.name", self.notes[0])
300
301 def test_extra_excludes(self):
302 self.path = self.cfg_path(mirror={"repo": self.repo, "exclude": ["secret/"]})
303 self.write("secret/x.md", "x")
304 self.settle(self.path)
305 self.assertEqual(git(self.repo, "ls-files").split(), ["one.md"])
306
307 def test_push_goes_to_the_remote_and_failure_does_not_stop_deploy(self):
308 remote = os.path.join(self.dir, "remote.git")
309 subprocess.run(["git", "init", "-q", "--bare", remote], check=True)
310 self.path = self.cfg_path(mirror={"repo": self.repo, "remote": "origin"}, autodeploy={})
311 self.baseline()
312 self.write("seed", "x", base=self.repo)
313 subprocess.run(["git", "init", "-q", "-b", "dropbox-mirror", self.repo], check=True)
314 git(self.repo, "add", "-A")
315 git(self.repo, "commit", "-q", "-m", "seed")
316 git(self.repo, "remote", "add", "origin", remote)
317 self.built["index.html"] = "<p>changed</p>"
318 self.assertEqual(self.settle(self.path), "deployed")
319 self.assertEqual(git(remote, "log", "--format=%s", "dropbox-mirror").splitlines()[0][:9], "Mirror of")
320 self.assertEqual(git(remote, "branch", "--format=%(refname:short)").split(), ["dropbox-mirror"])
321 # now the remote disappears: the push fails, the notification says so, the deploy still happens
322 shutil.rmtree(remote)
323 self.notes.clear()
324 self.write("one.md", "# One\n\nagain\n")
325 self.built["index.html"] = "<p>changed again</p>"
326 self.assertEqual(self.settle(self.path), "deployed")
327 self.assertEqual(len(self.deploys), 2)
328 self.assertEqual(len(self.notes), 1)
329 self.assertIn("push", self.notes[0])
330
331 def test_dry_run_writes_nothing(self):
332 lines = []
333 env = self.env(echo=lines.append)
334 bw.dry_run(self.path, env)
335 self.assertIn("git init", "\n".join(lines))
336 self.assertFalse(os.path.exists(self.repo))
337 self.assertFalse(os.path.exists(os.path.join(self.sd, "state.json")))
338 self.settle(self.path)
339 self.write("two.md", "x")
340 lines.clear()
341 bw.dry_run(self.path, env)
342 self.assertIn("two.md", "\n".join(lines))
343 self.assertEqual(len(self.commits()), 1)
344 self.assertFalse(os.path.exists(os.path.join(self.repo, "two.md")))
345
346 def test_repo_inside_source_is_refused(self):
347 path = self.cfg_path(mirror={"repo": os.path.join(self.src, "repo")})
348 self.assertEqual(self.settle(path), "blocked")
349
350
351class Guard(WatchCase):
352 def setUp(self):
353 super().setUp()
354 self.path = self.cfg_path(autodeploy={})
355
356 def test_no_baseline_holds(self):
357 self.assertEqual(self.settle(self.path), "held")
358 self.assertIn("no baseline", self.notes[0])
359 self.assertEqual(self.deploys, [])
360 self.assertTrue(self.state()["handled"])
361
362 def test_added_file_holds(self):
363 self.baseline()
364 self.built["new/index.html"] = "<p>new</p>"
365 self.assertEqual(self.settle(self.path), "held")
366 self.assertIn("1 added, 0 removed", self.notes[0])
367 self.assertIn("fw blog deploy", self.notes[0])
368 self.assertIn("+new/index.html", self.log())
369 self.assertEqual(self.deploys, [])
370
371 def test_removed_file_holds(self):
372 self.baseline()
373 del self.built["a/index.html"]
374 self.assertEqual(self.settle(self.path), "held")
375 self.assertIn("0 added, 1 removed", self.notes[0])
376 self.assertEqual(self.deploys, [])
377
378 def test_same_paths_changed_content_deploys_once(self):
379 self.baseline()
380 self.built["a/index.html"] = "<p>a, edited</p>"
381 self.assertEqual(self.settle(self.path), "deployed")
382 self.assertEqual(len(self.deploys), 1)
383 self.assertEqual(self.notes, []) # no notification for a success
384 self.assertIn("deployed: 1 files changed", self.log())
385 self.clock.advance(1000)
386 self.assertEqual(self.tick(self.path), "idle")
387 self.assertEqual(len(self.deploys), 1)
388 # the baseline moved on: an identical build later changes nothing
389 self.write("one.md", "# One\n\nsmall edit\n")
390 self.assertEqual(self.settle(self.path), "unchanged")
391 self.assertEqual(len(self.deploys), 1)
392
393 def test_identical_output_does_not_deploy(self):
394 self.baseline()
395 self.assertEqual(self.settle(self.path), "unchanged")
396 self.assertEqual(self.deploys, [])
397 self.assertEqual(self.notes, [])
398 self.assertIn("no visible change", self.log())
399 self.assertTrue(self.state()["handled"])
400
401 def test_deploy_failure_notifies_once_and_is_handled(self):
402 self.baseline()
403 self.built["a/index.html"] = "<p>edited</p>"
404
405 def failing(cfg, out):
406 raise blog.BlogError("rsync failed (exit 12)")
407 self.assertEqual(self.settle(self.path, deploy=failing), "deploy-error")
408 self.assertEqual(len(self.notes), 1)
409 self.assertTrue(self.state()["handled"])
410 self.assertEqual(self.tick(self.path), "idle")
411 self.assertEqual(len(self.notes), 1)
412
413 def test_build_error_notifies_once(self):
414 self.baseline()
415
416 def broken(cfg, out):
417 raise blog.BlogError("post.md: a code fence is never closed")
418 self.assertEqual(self.settle(self.path, build=broken), "build-error")
419 self.assertEqual(self.tick(self.path, build=broken), "idle")
420 self.assertEqual(len(self.notes), 1)
421 self.assertIn("code fence", self.notes[0])
422 self.assertTrue(self.state()["handled"])
423 self.write("one.md", "# One\n\nfixed\n") # a later change retries
424 self.assertEqual(self.settle(self.path), "unchanged")
425
426 @needs_markdown
427 def test_real_build_with_unclosed_fence_is_refused(self):
428 self.config["posts"] = {"2026-01-01-p.md": {"published": True}}
429 self.path = self.cfg_path()
430 self.write("2026-01-01-p.md", "# P\n\n## Writing\n\n```\nunclosed\n\n## Spelling\n\nsecret\n")
431 self.baseline()
432 self.assertEqual(self.settle(self.path, build=bw.build_site), "build-error")
433 self.assertIn("code fence", self.notes[0])
434 self.assertEqual(self.deploys, [])
435
436 @needs_markdown
437 def test_real_build_is_deterministic_and_manifest_matches(self):
438 self.config["posts"] = {"2026-01-01-p.md": {"published": True}}
439 self.path = self.cfg_path()
440 self.write("2026-01-01-p.md", "# P\n\n## Writing\n\nhello\n")
441 cfg = blog.load_config(self.path)
442 a, b = os.path.join(self.dir, "a"), os.path.join(self.dir, "b")
443 blog.build(cfg, a)
444 blog.build(cfg, b)
445 self.assertEqual(blog.manifest(a), blog.manifest(b))
446 self.assertNotIn(blog.MARKER, blog.manifest(a))
447
448
449class ManualDeploy(WatchCase):
450 def test_real_deploy_writes_baseline_and_dry_run_does_not(self):
451 path = self.cfg_path()
452 cfg = blog.load_config(path)
453 out = os.path.join(self.dir, "out")
454 calls = []
455
456 class Done:
457 returncode = 0
458 run = lambda cmd, **kw: calls.append(cmd) or Done() # noqa: E731
459 self.built = {"index.html": "<p>x</p>", "robots.txt": "User-agent: *\n"}
460 os.makedirs(out)
461 blog.prepare_out(out)
462 self.fake_build(cfg, out)
463 blog.deploy_site(cfg, out, dry_run=True, prebuilt=True, run=run)
464 self.assertFalse(os.path.exists(os.path.join(self.sd, "deployed.json")))
465 self.assertIn("-n", calls[0])
466 self.assertEqual(calls[0][0], "rsync")
467 asked = []
468 blog.deploy_site(cfg, out, prebuilt=True, run=run, confirm=lambda t: asked.append(t) or True)
469 self.assertEqual(asked, ["dh:writing.example.org"])
470 cmd = calls[1]
471 self.assertEqual(cmd[1:1 + len(blog.RSYNC_OPTS)], blog.RSYNC_OPTS) # the protective excludes stay
472 self.assertIn("/_comments/", cmd)
473 self.assertIn(".well-known", cmd)
474 self.assertEqual(cmd[-2:], [out + "/", "dh:writing.example.org/"]) # source first, then target
475 with open(os.path.join(self.sd, "deployed.json")) as f:
476 data = json.load(f)
477 self.assertEqual(sorted(data["files"]), ["index.html", "robots.txt"])
478 self.assertIn("time", data)
479
480 def test_declined_or_failed_upload_leaves_baseline_alone(self):
481 path = self.cfg_path()
482 cfg = blog.load_config(path)
483 out = os.path.join(self.dir, "out")
484 blog.prepare_out(out)
485 self.fake_build(cfg, out)
486
487 class Failed:
488 returncode = 12
489 with self.assertRaises(blog.BlogError):
490 blog.deploy_site(cfg, out, prebuilt=True, run=lambda cmd, **kw: Failed(), confirm=lambda t: False)
491 with self.assertRaises(blog.BlogError):
492 blog.deploy_site(cfg, out, prebuilt=True, run=lambda cmd, **kw: Failed())
493 self.assertFalse(os.path.exists(os.path.join(self.sd, "deployed.json")))
494
495 def test_audit_still_runs_before_upload(self):
496 cfg = blog.load_config(self.cfg_path())
497 out = os.path.join(self.dir, "out")
498 blog.prepare_out(out)
499 self.write("notes.md", "private", base=out)
500 with self.assertRaises(blog.BlogError):
501 blog.deploy_site(cfg, out, prebuilt=True, run=lambda cmd, **kw: self.fail("rsync must not run"))
502
503
504class ConfigKeys(WatchCase):
505 def bad(self, **extra):
506 with self.assertRaises(blog.BlogError):
507 blog.load_config(self.cfg_path(**extra))
508
509 def test_valid(self):
510 cfg = blog.load_config(self.cfg_path(autodeploy={"quiet_seconds": 60},
511 mirror={"repo": "~/x", "branch": "a/b-c_1.2", "remote": "origin",
512 "exclude": ["*.tmp", "/drafts"]}))
513 self.assertEqual(cfg["autodeploy"]["quiet_seconds"], 60)
514
515 def test_autodeploy(self):
516 for value in ({"quiet_seconds": 59}, {"quiet_seconds": "300"}, {"quiet_seconds": True}, {"other": 1}, []):
517 self.bad(autodeploy=value)
518
519 def test_mirror(self):
520 for value in ({}, {"repo": ""}, {"repo": 5}, {"repo": "r", "branch": "-x"}, {"repo": "r", "branch": "a b"},
521 {"repo": "r", "branch": "a..b"}, {"repo": "r", "remote": "a/b"}, {"repo": "r", "remote": "-x"},
522 {"repo": "r", "exclude": "x"}, {"repo": "r", "exclude": ["../x"]},
523 {"repo": "r", "exclude": ["/../x"]}, {"repo": "r", "exclude": [1]}, {"repo": "r", "extra": 1},
524 {"repo": "r", "exclude": ["!x"]}, {"repo": "r", "exclude": ["+ x"]},
525 {"repo": "r", "exclude": ["-x"]}, {"repo": "r", "exclude": [":x"]},
526 {"repo": "r", "branch": "main"}, {"repo": "r", "branch": "master"}, {"repo": "r", "branch": "HEAD"}):
527 self.config.pop("mirror", None)
528 self.bad(mirror=value)
529
530
531class Plist(WatchCase):
532 def test_content(self):
533 path = self.cfg_path()
534 data = plistlib.loads(bw.plist_text(path, fw="/opt/fw/bin/fw").encode())
535 self.assertEqual(data["Label"], "net.fuzzyworld.fw-blog-watch-" + blog.watch_name(path))
536 self.assertEqual(data["ProgramArguments"], ["/opt/fw/bin/fw", "blog", "watch", os.path.abspath(path), "--once"])
537 self.assertEqual(data["StartInterval"], 60)
538 self.assertTrue(data["RunAtLoad"])
539 self.assertEqual(data["EnvironmentVariables"]["PATH"], "/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin")
540 self.assertEqual(data["StandardOutPath"], os.path.join(self.sd, "launchd.log"))
541 self.assertEqual(data["StandardErrorPath"], os.path.join(self.sd, "launchd.log"))
542 self.assertEqual((data["ProcessType"], data["Nice"]), ("Background", 10))
543
544 def test_install_and_uninstall_with_a_fake_launchctl(self):
545 path = self.cfg_path()
546 agents = os.path.join(self.dir, "LaunchAgents")
547 calls = []
548
549 class Ok:
550 returncode, stderr = 0, ""
551 run = lambda cmd, **kw: calls.append(cmd) or Ok() # noqa: E731
552 plist = bw.install(path, run=run, agents_dir=agents, uid=501)
553 self.assertEqual(plist, os.path.join(agents, "net.fuzzyworld.fw-blog-watch-" + blog.watch_name(path) + ".plist"))
554 self.assertTrue(os.path.exists(plist))
555 self.assertEqual(calls[-1], ["launchctl", "bootstrap", "gui/501", plist])
556 bw.uninstall(path, run=run, agents_dir=agents, uid=501)
557 self.assertEqual(calls[-1], ["launchctl", "bootout", "gui/501", plist])
558 self.assertFalse(os.path.exists(plist))
559
560 def test_print_flag_writes_nothing(self):
561 path = self.cfg_path()
562 proc = subprocess.run([sys.executable, os.path.join(bw.HERE, "blog_watch.py"), "install", path, "--print"],
563 capture_output=True, text=True, env={**os.environ, "HOME": self.dir})
564 self.assertEqual(proc.returncode, 0, proc.stderr)
565 self.assertIn("net.fuzzyworld.fw-blog-watch-" + blog.watch_name(path), proc.stdout)
566 self.assertFalse(os.path.exists(os.path.join(self.dir, "Library")))
567
568
569class Robustness(WatchCase):
570 def test_hash_cache_skips_unchanged_files(self):
571 cache = {}
572 a, _ = bw.scan(self.src, cache)
573 with mock.patch.object(bw, "file_hash", side_effect=AssertionError("read again")):
574 b, _ = bw.scan(self.src, cache)
575 self.assertEqual(a, b)
576
577 def test_cache_entry_is_reused_only_for_an_identical_stamp(self):
578 cache = {}
579 bw.scan(self.src, cache)
580 for i in range(4): # size, mtime, inode, ctime
581 tampered = {k: list(v) for k, v in cache.items()}
582 tampered["one.md"][i] += 1
583 tampered["one.md"][4] = "stale"
584 bw.scan(self.src, tampered)
585 self.assertNotEqual(tampered["one.md"][4], "stale", i)
586 again = {k: list(v) for k, v in cache.items()}
587 again["one.md"][4] = "kept"
588 bw.scan(self.src, again)
589 self.assertEqual(again["one.md"][4], "kept") # untouched stamp: not re-read
590
591 def test_malformed_hash_cache_is_ignored(self):
592 path = self.cfg_path(autodeploy={})
593 os.makedirs(self.sd)
594 for junk in ("{not json", "[1, 2]", '{"one.md": "x"}', '{"one.md": [1, 2]}', '{"one.md": [0, 0, 0, 0, 5]}'):
595 with open(os.path.join(self.sd, "hashes.json"), "w") as f:
596 f.write(junk)
597 self.assertIn(self.tick(path), ("changed", "waiting", "idle"))
598 with open(os.path.join(self.sd, "hashes.json")) as f:
599 self.assertEqual(sorted(json.load(f)), ["one.md"])
600
601 def test_run_command_times_out_as_a_failure(self):
602 result = bw.run_command(["sleep", "5"], timeout=0.2)
603 self.assertEqual(result.returncode, 124)
604 self.assertIn("timed out", result.stderr)
605
606 def test_unexpected_exception_is_logged_and_notified_once(self):
607 path = self.cfg_path(autodeploy={})
608 with mock.patch.object(bw, "scan", side_effect=RuntimeError("boom")):
609 self.assertEqual(self.tick(path), "error")
610 self.assertEqual(self.tick(path), "error")
611 self.assertEqual(len(self.notes), 1)
612 self.assertIn("boom", self.notes[0])
613 self.assertIn("boom", self.log())
614 self.assertEqual(self.tick(path), "changed") # and the next tick works again
615 # --once exits 0 even then
616 with mock.patch.object(bw, "scan", side_effect=RuntimeError("boom")), \
617 mock.patch.object(sys, "stderr", new=io.StringIO()):
618 bw.main(["blog_watch.py", path, "--once"])
619
620 def test_config_error_recovery_notifies_again_next_time(self):
621 good = {"quiet_seconds": 300}
622 path = self.cfg_path(autodeploy={"quiet_seconds": 5})
623 self.tick(path)
624 self.tick(path)
625 self.assertEqual(len(self.notes), 1)
626 path = self.cfg_path(autodeploy=good)
627 self.assertEqual(self.tick(path), "changed")
628 self.assertNotIn("config_error", self.state())
629 path = self.cfg_path(autodeploy={"quiet_seconds": 5})
630 self.tick(path)
631 self.assertEqual(len(self.notes), 2)
632
633 def test_missing_source_folder_notifies_once(self):
634 path = self.cfg_path(autodeploy={})
635 shutil.rmtree(self.src)
636 self.assertEqual(self.tick(path), "config-error")
637 self.assertEqual(self.tick(path), "config-error")
638 self.assertEqual(len(self.notes), 1)
639 self.assertIn("not found", self.notes[0])
640 lines = []
641 bw.dry_run(path, self.env(echo=lines.append))
642 self.assertIn("not found", lines[0])
643
644 def test_source_change_during_build_aborts_the_deploy(self):
645 path = self.cfg_path(autodeploy={})
646 self.baseline()
647 self.built["a/index.html"] = "<p>edited</p>"
648
649 def build_and_edit(cfg, out):
650 self.fake_build(cfg, out)
651 self.write("one.md", "# One\n\nedited while building\n")
652 self.assertEqual(self.settle(path, build=build_and_edit), "changed-during-build")
653 self.assertEqual(self.deploys, [])
654 self.assertFalse(self.state()["handled"])
655 self.assertIn("changed during build", self.log())
656 self.assertEqual(self.tick(path), "changed") # a new quiet period starts
657 self.clock.advance(301)
658 self.assertEqual(self.tick(path), "deployed")
659
660 def test_stuck_lock_holder_is_reported_once(self):
661 path = self.cfg_path(autodeploy={})
662 sd = self.sd
663 held = blog.acquire_lock(sd, now=lambda: self.clock.t - 4000)
664 self.addCleanup(held.close)
665 self.assertEqual(self.tick(path), "locked")
666 self.assertEqual(self.tick(path), "locked")
667 self.assertEqual(len(self.notes), 1)
668 self.assertIn("stuck", self.notes[0])
669
670 def test_state_dir_is_keyed_by_folder_and_path(self):
671 del os.environ["FW_BLOG_WATCH_DIR"]
672 a, b = os.path.join(self.dir, "x", "Blog", "fw-blog.json"), os.path.join(self.dir, "y", "Blog", "fw-blog.json")
673 self.assertRegex(blog.watch_name(a), r"^blog-[0-9a-f]{8}$")
674 self.assertNotEqual(blog.watch_name(a), blog.watch_name(b))
675 self.assertTrue(blog.state_dir(a).endswith(os.path.join(".fw-blog-watch", blog.watch_name(a))))
676
677 def test_install_retries_bootstrap(self):
678 path = self.cfg_path()
679 calls, naps = [], []
680
681 class R:
682 def __init__(self, code):
683 self.returncode, self.stderr = code, "busy"
684
685 def run(cmd, **kw):
686 calls.append(cmd[1])
687 return R(5 if cmd[1] == "bootstrap" and calls.count("bootstrap") < 3 else 0)
688 bw.install(path, run=run, agents_dir=os.path.join(self.dir, "LA"), uid=1, sleep=naps.append)
689 self.assertEqual(calls.count("bootstrap"), 3)
690 self.assertEqual(naps, [1, 1])
691 calls.clear()
692 with self.assertRaises(blog.BlogError):
693 bw.install(path, run=lambda cmd, **kw: R(5), agents_dir=os.path.join(self.dir, "LA"), uid=1,
694 sleep=naps.append)
695
696
697class GeneratorGuard(WatchCase):
698 def setUp(self):
699 super().setUp()
700 self.path = self.cfg_path(autodeploy={})
701
702 def test_generator_change_holds(self):
703 self.baseline(generator="old")
704 self.built["a/index.html"] = "<p>edited</p>"
705 self.assertEqual(self.settle(self.path), "held")
706 self.assertIn("generator changed", self.notes[0])
707 self.assertEqual(self.deploys, [])
708
709 def test_deploy_target_change_holds(self):
710 self.baseline()
711 self.path = self.cfg_path(deploy={"host": "dh", "dir": "other.example.org"}, autodeploy={})
712 self.built["a/index.html"] = "<p>edited</p>"
713 self.assertEqual(self.settle(self.path), "held")
714 self.assertIn("deploy target changed", self.notes[0])
715 self.assertEqual(self.deploys, [])
716
717 def test_config_change_holds(self):
718 self.baseline()
719 self.path = self.cfg_path(title="A new title", autodeploy={})
720 self.built["a/index.html"] = "<p>edited</p>"
721 self.assertEqual(self.settle(self.path), "held")
722 self.assertIn("config changed", self.notes[0])
723 self.assertEqual(self.deploys, [])
724
725 def test_deployed_json_records_generator_config_and_target(self):
726 self.baseline()
727 self.built["a/index.html"] = "<p>edited</p>"
728 self.assertEqual(self.settle(self.path), "deployed") # the watcher's own deploy keeps them current
729 with open(os.path.join(self.sd, "deployed.json")) as f:
730 data = json.load(f)
731 self.assertEqual(data["generator"], blog.GENERATOR_HASH)
732 self.assertEqual(data["config"], blog.config_hash(blog.load_config(self.path)))
733 self.assertEqual(data["target"], "dh:writing.example.org")
734
735 def test_generator_hash_is_fixed_when_the_module_loads(self):
736 before = blog.GENERATOR_HASH
737 other = os.path.join(self.dir, "blogdir")
738 os.makedirs(other)
739 self.write("x.css", "changed", base=other)
740 with mock.patch.object(blog, "BLOG_DIR", other):
741 self.assertNotEqual(blog.generator_hash(), before) # a fresh computation sees the edit ...
742 self.assertEqual(blog.GENERATOR_HASH, before) # ... the value the running code uses does not
743 self.assertEqual(bw.Env().generator(), before)
744
745 def test_generator_hash_follows_each_input(self):
746 fake = os.path.join(self.dir, "srv")
747 for rel in ("blog.py", "atom.py", "gen.py", "site/_shared.css", "site/favicon.ico", "site-blog/blog.css"):
748 self.write(rel, "v1", base=fake)
749 with mock.patch.object(blog, "HERE", fake), mock.patch.object(blog, "SITE_DIR", os.path.join(fake, "site")), \
750 mock.patch.object(blog, "BLOG_DIR", os.path.join(fake, "site-blog")):
751 seen = {blog.generator_hash()}
752 for rel in ("blog.py", "atom.py", "gen.py", "site/_shared.css", "site-blog/blog.css"):
753 self.write(rel, "v2 " + rel, base=fake)
754 seen.add(blog.generator_hash())
755 self.assertEqual(len(seen), 6) # every edit changed the hash
756
757 def test_dry_run_reports_each_decision(self):
758 lines = []
759 env = self.env(echo=lines.append)
760 bw.dry_run(self.path, env)
761 self.assertIn("no baseline", lines[-1])
762 self.baseline()
763 lines.clear()
764 self.built["a/index.html"] = "<p>edited</p>"
765 bw.dry_run(self.path, env)
766 self.assertIn("would upload (1 files changed)", lines[-1])
767 self.assertFalse(os.path.exists(os.path.join(self.sd, "state.json")))
768 self.assertEqual(self.deploys, [])
769
770
771class MirrorRecovery(WatchCase):
772 def setUp(self):
773 super().setUp()
774 self.repo = os.path.join(self.dir, "repo")
775 self.path = self.cfg_path(mirror={"repo": self.repo})
776
777 def commits(self):
778 return git(self.repo, "log", "--format=%s").splitlines()
779
780 def run_with_rsync_code(self, code):
781 def run(cmd, cwd=None, timeout=None):
782 result = bw.run_command(cmd, cwd=cwd, timeout=timeout or 120)
783 if cmd[0] == "rsync" and result.returncode == 0:
784 return subprocess.CompletedProcess(cmd, code, result.stdout, "some files vanished")
785 return result
786 return run
787
788 def test_rsync_24_is_retried_over_our_own_dirt(self):
789 self.write("one.md", "# One\n\nv2\n")
790 self.assertEqual(self.settle(self.path, run=self.run_with_rsync_code(24)), "blocked")
791 self.assertEqual(self.notes, []) # 24 is normal while Dropbox syncs
792 self.assertIn("mirror_dirty", self.state())
793 self.assertFalse(self.state()["handled"])
794 self.assertEqual(self.tick(self.path, run=self.run_with_rsync_code(24)), "blocked") # still ours
795 self.assertEqual(self.tick(self.path), "mirrored")
796 self.assertNotIn("mirror_dirty", self.state())
797 self.assertEqual(len(self.commits()), 1)
798
799 def test_rsync_23_notifies_once_and_recovers(self):
800 self.assertEqual(self.settle(self.path, run=self.run_with_rsync_code(23)), "blocked")
801 self.tick(self.path, run=self.run_with_rsync_code(23))
802 self.assertEqual(len(self.notes), 1)
803 self.assertIn("rsync", self.notes[0])
804 self.assertEqual(self.tick(self.path), "mirrored")
805
806 def ignoring_source(self):
807 self.write(".gitignore", "*.log\n")
808 self.write("run.log", "kept out of git\n")
809
810 def test_ignored_leftovers_are_accepted_only_as_recorded(self):
811 self.ignoring_source()
812 self.assertEqual(self.settle(self.path), "mirrored")
813 self.assertIn("run.log", json.dumps(self.state()["mirror_dirty"]))
814 self.write("one.md", "# One\n\nsecond edit\n")
815 self.assertEqual(self.settle(self.path), "mirrored") # the recorded leftovers are ours
816 self.assertEqual(len(self.commits()), 2)
817
818 def test_human_edit_of_a_tracked_file_blocks_despite_the_record(self):
819 self.ignoring_source()
820 self.settle(self.path)
821 with open(os.path.join(self.repo, "one.md"), "w") as f:
822 f.write("my own work in the repo\n")
823 self.write("one.md", "# One\n\nsource edit\n")
824 self.assertEqual(self.settle(self.path), "blocked")
825 with open(os.path.join(self.repo, "one.md")) as f:
826 self.assertEqual(f.read(), "my own work in the repo\n") # preserved
827 self.assertIn("uncommitted", self.notes[-1])
828
829 def test_human_edit_of_a_leftover_file_blocks(self):
830 self.ignoring_source()
831 self.settle(self.path)
832 self.write("run.log", "my notes\n", base=self.repo)
833 self.write("one.md", "# One\n\nsource edit\n")
834 self.assertEqual(self.settle(self.path), "blocked")
835
836 def test_new_path_beside_the_record_blocks(self):
837 self.ignoring_source()
838 self.settle(self.path)
839 self.write("other.log", "new\n", base=self.repo)
840 self.write("one.md", "# One\n\nsource edit\n")
841 self.assertEqual(self.settle(self.path), "blocked")
842
843 def test_non_ascii_and_odd_names_in_the_record(self):
844 names = ["заметки.log", "a -> b.log", "with space.log"]
845 self.write(".gitignore", "*.log\n")
846 for name in names:
847 self.write(name, "kept out of git\n")
848 self.assertEqual(self.settle(self.path), "mirrored")
849 recorded = self.state()["mirror_dirty"]["status"]
850 for name in names:
851 self.assertIn("!! " + name, recorded)
852 self.write("one.md", "# One\n\nsecond edit\n")
853 self.assertEqual(self.settle(self.path), "mirrored") # untouched leftovers are accepted
854 for name in names:
855 self.write(name, "my notes\n", base=self.repo)
856 self.write("one.md", "# One\n\nedit after " + name + "\n")
857 self.assertEqual(self.settle(self.path), "blocked", name)
858 with open(os.path.join(self.repo, name), encoding="utf-8") as f:
859 self.assertEqual(f.read(), "my notes\n") # preserved
860 os.remove(os.path.join(self.repo, name))
861 self.write(name, "kept out of git\n", base=self.repo) # put the leftover back as it was
862
863 def test_record_for_another_repo_is_ignored(self):
864 self.ignoring_source()
865 self.settle(self.path)
866 state = self.state()
867 state["mirror_dirty"]["repo"] = "/somewhere/else"
868 with open(os.path.join(self.sd, "state.json"), "w") as f:
869 json.dump(state, f)
870 self.write("one.md", "# One\n\nsource edit\n")
871 self.assertEqual(self.settle(self.path), "blocked")
872
873 def test_marker_does_not_excuse_a_changed_head(self):
874 self.settle(self.path)
875 self.write("one.md", "# One\n\nv2\n")
876 self.assertEqual(self.settle(self.path, run=self.run_with_rsync_code(24)), "blocked")
877 git(self.repo, "commit", "-q", "-a", "-m", "by hand") # HEAD moved: the dirt is no longer provably ours
878 self.write("stray.txt", "x", base=self.repo)
879 self.assertEqual(self.tick(self.path), "blocked")
880 self.assertIn("uncommitted", self.notes[-1])
881
882 def test_relative_repo_is_relative_to_the_config_folder(self):
883 path = self.cfg_path(mirror={"repo": "../repo-rel"})
884 self.assertEqual(self.settle(path), "mirrored")
885 self.assertTrue(os.path.isdir(os.path.join(self.dir, "repo-rel", ".git")))
886
887 def test_git_ignored_files_count_as_dirty(self):
888 self.settle(self.path)
889 self.write(".gitignore", "*.log\n", base=self.repo)
890 git(self.repo, "add", ".gitignore")
891 git(self.repo, "commit", "-q", "-m", "ignore")
892 self.write("keep.log", "mine", base=self.repo)
893 self.write("one.md", "# One\n\nv2\n")
894 self.assertEqual(self.settle(self.path), "blocked")
895 self.assertTrue(os.path.exists(os.path.join(self.repo, "keep.log")))
896
897 def test_user_excludes_come_before_the_protective_git_exclude(self):
898 cmd = bw.rsync_command("/s", "/r", ["secret/"])
899 self.assertLess(cmd.index("--exclude=secret/"), cmd.index("--exclude=/.git"))
900 self.assertEqual(cmd[-2:], ["/s/", "/r/"])
901
902 def test_push_uses_explicit_refspec(self):
903 calls = []
904 base = bw.run_command
905
906 def run(cmd, cwd=None, timeout=None):
907 calls.append(cmd)
908 return base(cmd, cwd=cwd, timeout=timeout or 120)
909 remote = os.path.join(self.dir, "r.git")
910 subprocess.run(["git", "init", "-q", "--bare", remote], check=True)
911 path = self.cfg_path(mirror={"repo": self.repo, "remote": "origin"})
912 os.makedirs(self.repo)
913 subprocess.run(["git", "init", "-q", "-b", "dropbox-mirror", self.repo], check=True)
914 git(self.repo, "remote", "add", "origin", remote)
915 self.settle(path, run=run)
916 pushes = [c for c in calls if "push" in c]
917 self.assertEqual(pushes[0][-2:], ["origin", "refs/heads/dropbox-mirror:refs/heads/dropbox-mirror"])
918
919
920class DeployCommand(WatchCase):
921 def test_main_passes_flags_and_exit_codes(self):
922 path = self.cfg_path()
923 out = os.path.join(self.dir, "o")
924 with mock.patch.object(blog, "deploy_site") as deploy:
925 blog.main(["blog.py", "deploy", path, "--out", out, "--yes"])
926 self.assertIsNone(deploy.call_args.kwargs["confirm"])
927 self.assertFalse(deploy.call_args.kwargs["dry_run"])
928 blog.main(["blog.py", "deploy", path, "--out", out, "--dry-run"])
929 self.assertTrue(deploy.call_args.kwargs["dry_run"])
930 self.assertIs(deploy.call_args.kwargs["confirm"], blog.ask_to_upload)
931 deploy.side_effect = blog.BlogError("rsync failed (exit 12)")
932 with self.assertRaises(SystemExit) as caught:
933 blog.main(["blog.py", "deploy", path, "--out", out, "--yes"])
934 self.assertIn("rsync failed", str(caught.exception.code))
935
936 @needs_markdown
937 def test_not_a_terminal_refuses_without_yes(self):
938 path = self.cfg_path()
939 out = os.path.join(self.dir, "o")
940 with mock.patch.object(sys.stdin, "isatty", return_value=False), \
941 mock.patch.object(blog.subprocess, "run", side_effect=AssertionError("rsync must not run")):
942 with self.assertRaises(SystemExit) as caught:
943 blog.main(["blog.py", "deploy", path, "--out", out])
944 self.assertIn("not a terminal", str(caught.exception.code))
945
946 def test_eof_at_the_prompt_declines(self):
947 with mock.patch.object(sys.stdin, "isatty", return_value=True), mock.patch("builtins.input", side_effect=EOFError):
948 self.assertFalse(blog.ask_to_upload("dh:x"))
949
950 def test_ctrl_c_at_the_prompt_exits_quietly_with_1(self):
951 with mock.patch.object(sys.stdin, "isatty", return_value=True), \
952 mock.patch("builtins.input", side_effect=KeyboardInterrupt), mock.patch.object(sys, "stderr", new=io.StringIO()):
953 with self.assertRaises(SystemExit) as caught:
954 blog.ask_to_upload("dh:x")
955 self.assertEqual(caught.exception.code, 1)
956
957 def test_lock_is_taken_after_the_answer_and_manual_rsync_has_no_timeout(self):
958 cfg = blog.load_config(self.cfg_path())
959 out = os.path.join(self.dir, "out")
960 blog.prepare_out(out)
961 self.fake_build(cfg, out)
962 seen = {}
963
964 class Done:
965 returncode = 0
966
967 def confirm(target):
968 lock = blog.acquire_lock(self.sd) # free while the question is open
969 seen["free"] = lock is not None
970 if lock:
971 lock.close()
972 return True
973 blog.deploy_site(cfg, out, prebuilt=True, confirm=confirm,
974 run=lambda cmd, **kw: seen.update(kw) or Done())
975 self.assertTrue(seen["free"])
976 self.assertIsNone(seen["timeout"])
977 with mock.patch.object(blog, "deploy_site") as deploy:
978 bw.deploy_built(cfg, out)
979 self.assertEqual(deploy.call_args.kwargs["timeout"], 600)
980 self.assertTrue(deploy.call_args.kwargs["locked"])
981
982 def test_watcher_deploy_while_answering_refuses_the_manual_upload(self):
983 cfg = blog.load_config(self.cfg_path())
984 out = os.path.join(self.dir, "out")
985 blog.prepare_out(out)
986 self.fake_build(cfg, out)
987 self.baseline()
988
989 def confirm(target): # the watcher deploys while the question is open
990 blog.write_deployed(self.sd, {"index.html": "x"}, "2030-01-01T00:00:00Z", cfg=cfg)
991 return True
992 with self.assertRaises(blog.BlogError) as caught:
993 blog.deploy_site(cfg, out, prebuilt=True, confirm=confirm, run=lambda cmd, **kw: self.fail("no rsync"))
994 self.assertIn("watcher deployed while you were answering", str(caught.exception))
995 self.assertIsNotNone(blog.acquire_lock(self.sd)) # and the lock was released
996
997 def test_manual_upload_resets_the_watchers_handled_state(self):
998 cfg = blog.load_config(self.cfg_path())
999 out = os.path.join(self.dir, "out")
1000 blog.prepare_out(out)
1001 self.fake_build(cfg, out)
1002 os.makedirs(self.sd, exist_ok=True)
1003 with open(os.path.join(self.sd, "state.json"), "w") as f:
1004 json.dump({"fingerprint": "x", "handled": True, "conflicts": [], "changed_at": 5}, f)
1005
1006 class Done:
1007 returncode = 0
1008 blog.deploy_site(cfg, out, prebuilt=True, run=lambda cmd, **kw: Done())
1009 with open(os.path.join(self.sd, "state.json")) as f:
1010 state = json.load(f)
1011 self.assertNotIn("fingerprint", state)
1012 self.assertNotIn("handled", state)
1013 self.assertEqual(state["changed_at"], 5)
1014 self.cfg_path(autodeploy={})
1015 self.assertEqual(self.tick(self.cfg_file), "changed") # the next tick re-evaluates
1016
1017 def test_manual_deploy_is_refused_while_a_tick_holds_the_lock(self):
1018 cfg = blog.load_config(self.cfg_path())
1019 out = os.path.join(self.dir, "out")
1020 blog.prepare_out(out)
1021 self.fake_build(cfg, out)
1022 held = blog.acquire_lock(self.sd)
1023 self.addCleanup(held.close)
1024 with self.assertRaises(blog.BlogError) as caught:
1025 blog.deploy_site(cfg, out, prebuilt=True, run=lambda cmd, **kw: self.fail("no rsync"))
1026 self.assertIn("try again in a minute", str(caught.exception))
1027
1028 class Done:
1029 returncode = 0
1030 # the watcher itself holds the lock, so its own deploy path must not take it again; a dry run never needs it
1031 blog.deploy_site(cfg, out, prebuilt=True, locked=True, run=lambda cmd, **kw: Done())
1032 blog.deploy_site(cfg, out, prebuilt=True, dry_run=True, run=lambda cmd, **kw: Done())
1033
1034 @needs_markdown
1035 def test_bin_fw_deploy_without_flags_reaches_the_prompt_check(self):
1036 path = self.cfg_path()
1037 env = {**os.environ, "TMPDIR": self.dir, "FW_PYLIB": blog.gen.PYLIB}
1038 proc = subprocess.run([os.path.join(bw.HERE, "..", "bin", "fw"), "blog", "deploy", path],
1039 capture_output=True, text=True, stdin=subprocess.DEVNULL, env=env)
1040 self.assertEqual(proc.returncode, 1, proc.stderr)
1041 self.assertIn("not a terminal", proc.stderr)
1042 proc = subprocess.run([os.path.join(bw.HERE, "..", "bin", "fw"), "blog", "deploy", path, "--bogus"],
1043 capture_output=True, text=True, stdin=subprocess.DEVNULL, env=env)
1044 self.assertEqual(proc.returncode, 2)
1045
1046 def test_bin_fw_watch_once_never_installs_libraries(self):
1047 path = self.cfg_path()
1048 env = {**os.environ, "FW_PYLIB": os.path.join(self.dir, "empty-pylib"), "PATH": os.environ["PATH"]}
1049 proc = subprocess.run([os.path.join(bw.HERE, "..", "bin", "fw"), "blog", "watch", path, "--once"],
1050 capture_output=True, text=True, stdin=subprocess.DEVNULL, env=env, timeout=60)
1051 self.assertEqual(proc.returncode, 1, proc.stderr)
1052 self.assertIn("missing", proc.stderr)
1053 self.assertFalse(os.path.exists(env["FW_PYLIB"]))
1054
1055
1056if __name__ == "__main__":
1057 unittest.main()