bjomarks: bookmarks, their store, search and import
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
9f7718ad8f
25 changed files with 6658 additions and 0 deletions
412
tests/bookmark.bjo
Normal file
412
tests/bookmark.bjo
Normal file
|
|
@ -0,0 +1,412 @@
|
|||
;; This Source Code Form is subject to the terms of the Mozilla Public
|
||||
;; License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
;; file, You can obtain one at http://mozilla.org/MPL/2.0/.
|
||||
|
||||
;; bjomarks/tests/bookmark.bjo — (bjomarks bookmark): stamps, the JSON of
|
||||
;; entries and documents, and the properties of the merge.
|
||||
;;
|
||||
;; bjo run tests/bookmark.bjo
|
||||
|
||||
(import (std prelude))
|
||||
(import (std test))
|
||||
(import (std test gen))
|
||||
(import (std test prop))
|
||||
(import (std datetime))
|
||||
(import (std uuid))
|
||||
(import (text json))
|
||||
(import (bjomarks bookmark))
|
||||
|
||||
(: (-> string Uuid))
|
||||
(defun (uuid text)
|
||||
(match (string->uuid text)
|
||||
((Some u) u)
|
||||
(None (panic! (str "not a uuid: " text)))))
|
||||
|
||||
(: (-> string Instant))
|
||||
(defun (at text)
|
||||
(match (iso8601->instant text)
|
||||
((Some i) i)
|
||||
(None (panic! (str "not an instant: " text)))))
|
||||
|
||||
(def id-a (uuid "0b9a2f0e-6a3c-4d7e-9f10-1a2b3c4d5e6f"))
|
||||
(def id-b (uuid "1c8b3e1f-7b4d-4e8f-a021-2b3c4d5e6f70"))
|
||||
(def id-c (uuid "2d7c4f20-8c5e-4f90-b132-3c4d5e6f7081"))
|
||||
(def phone (uuid "3f9c0d2a-1111-4222-8333-444455556666"))
|
||||
(def laptop (uuid "77b2e40e-aaaa-4bbb-8ccc-ddddeeeeffff"))
|
||||
|
||||
(: (-> long int Uuid Stamp))
|
||||
(defun (stamp-at ms counter device) (Stamp (ms ms) (counter counter) (device device)))
|
||||
|
||||
(def example-bookmark
|
||||
(Bookmark (id id-a) (url "https://example.org/") (title (Some "Example Domain"))
|
||||
(added (at "2026-11-11T09:12:00Z"))
|
||||
(tags ["async" "rust"])
|
||||
(archive (Some "https://web.archive.org/web/20261111091200/https://example.org/"))))
|
||||
|
||||
(def example-entry (live-entry (stamp-at 1762852320000L 2 phone) example-bookmark))
|
||||
|
||||
(: (-> string (Result string Entry)))
|
||||
(defun (parse-entry text)
|
||||
(match (parse-json text #:objects 'fields)
|
||||
((Ok j) (json->entry j))
|
||||
((Err why) (Err why))))
|
||||
|
||||
(: (-> (Result string Entry) string))
|
||||
(defun (error-of r)
|
||||
(match r
|
||||
((Ok _) "Ok")
|
||||
((Err why) why)))
|
||||
|
||||
;; 1762852320000 is 0x019a722fb300.
|
||||
(def stamp-a-text "019a722fb300-0002-3f9c0d2a-1111-4222-8333-444455556666")
|
||||
|
||||
;; ---- Stamps -------------------------------------------------------------------
|
||||
|
||||
(deftest "a stamp's text has fixed widths"
|
||||
(check (= (stamp->string (stamp-at 1762852320000L 2 phone)) stamp-a-text))
|
||||
(check (= (stamp->string (stamp-at 0L 0 laptop)) "000000000000-0000-77b2e40e-aaaa-4bbb-8ccc-ddddeeeeffff")))
|
||||
|
||||
(deftest "a stamp's text reads back"
|
||||
(check (= (string->stamp stamp-a-text) (Some (stamp-at 1762852320000L 2 phone))))
|
||||
(check (= (string->stamp "019A722FB300-0002-3f9c0d2a-1111-4222-8333-444455556666") None))
|
||||
(check (= (string->stamp "019a722fb300-0002-3F9C0D2A-1111-4222-8333-444455556666") None))
|
||||
(check (= (string->stamp "019a722fb300_0002-3f9c0d2a-1111-4222-8333-444455556666") None))
|
||||
(check (= (string->stamp "19a722fb300-0002-3f9c0d2a-1111-4222-8333-444455556666") None))
|
||||
(check (= (string->stamp "") None)))
|
||||
|
||||
(def gen-stamp
|
||||
(gen-let ((ms (gen-long-range 0L 281474976710655L))
|
||||
(counter (gen-int-range 0 65535))
|
||||
(device (gen-element (list phone laptop))))
|
||||
(stamp-at ms counter device)))
|
||||
|
||||
(deftest "the order of stamp texts is the order of stamps"
|
||||
(for-all ((a gen-stamp) (b gen-stamp))
|
||||
(check (= (string->stamp (stamp->string a)) (Some a)))
|
||||
(def by-text (compare (stamp->string a) (stamp->string b)))
|
||||
(def by-stamp (stamp-compare a b))
|
||||
(check (= (compare by-text 0) (compare by-stamp 0)))))
|
||||
|
||||
(deftest "the clock uses the wall clock when it is ahead"
|
||||
(def (Tuple c s) (clock-next clock-zero 1000L phone))
|
||||
(check (= s (stamp-at 1000L 0 phone)))
|
||||
(check (= (.last-ms c) 1000L)))
|
||||
|
||||
(deftest "the clock counts while the wall clock is behind"
|
||||
(def seen (clock-observe clock-zero (stamp-at 5000L 7 laptop)))
|
||||
(def (Tuple c s) (clock-next seen 1000L phone))
|
||||
(check (= s (stamp-at 5000L 8 phone)))
|
||||
(def (Tuple _c2 s2) (clock-next c 1000L phone))
|
||||
(check (= s2 (stamp-at 5000L 9 phone)))
|
||||
(check (> (stamp-compare s2 s) 0)))
|
||||
|
||||
(deftest "the clock moves a millisecond on when the counter is full"
|
||||
(def full (clock-observe clock-zero (stamp-at 5000L 65535 laptop)))
|
||||
(def (Tuple _c s) (clock-next full 5000L phone))
|
||||
(check (= s (stamp-at 5001L 0 phone))))
|
||||
|
||||
(deftest "a new stamp is later than all that the clock saw"
|
||||
(for-all ((seen gen-stamp) (wall (gen-long-range 0L 281474976710655L)))
|
||||
(def (Tuple _c s) (clock-next (clock-observe clock-zero seen) wall phone))
|
||||
(check (> (compare (Tuple (.ms s) (.counter s)) (Tuple (.ms seen) (.counter seen))) 0))))
|
||||
|
||||
;; ---- Bookmarks ----------------------------------------------------------------
|
||||
|
||||
(deftest "make-bookmark checks and cleans"
|
||||
(def (Ok b) (make-bookmark " https://example.org/a " #:tags ["b" " a" "" "b"]
|
||||
#:added (at "2026-11-11T09:12:00Z"))
|
||||
:leave-with (check-fail "make-bookmark refused a good address"))
|
||||
(check (= (.url b) "https://example.org/a"))
|
||||
(check (= (.tags b) ["a" "b"]))
|
||||
(check (= (.archive b) None))
|
||||
(check (= (.added b) (at "2026-11-11T09:12:00Z")))
|
||||
(check-match (make-bookmark "example.org") (Err _))
|
||||
(check-match (make-bookmark "http://exa mple.org") (Err _))
|
||||
(check-match (make-bookmark "https://example.org" #:archive (Some "web.archive.org/x")) (Err _))
|
||||
(check-match (make-bookmark "https://example.org"
|
||||
#:archive (Some "https://web.archive.org/web/2026/https://example.org"))
|
||||
(Ok _))
|
||||
(check (not (= (.id b) (match (make-bookmark "https://example.org/a") ((Ok b2) (.id b2)) ((Err _) (.id b)))))))
|
||||
|
||||
(deftest "changing tags and the archive link"
|
||||
(check (= (.tags (bookmark-with-tags example-bookmark ["z" "a" "z"])) ["a" "z"]))
|
||||
(check-match (bookmark-with-archive example-bookmark (Some "nonsense")) (Err _))
|
||||
(check (= (match (bookmark-with-archive example-bookmark None) ((Ok b) (.archive b)) ((Err _) (Some "x")))
|
||||
None)))
|
||||
|
||||
;; `n` copies of `c`.
|
||||
(: (-> char int string))
|
||||
(defun (repeat c n) (string-pad-left "" n #:with c))
|
||||
|
||||
(deftest "a title is one line, trimmed, and not empty"
|
||||
#:cases ((text wanted)
|
||||
("Example Domain" (Some "Example Domain"))
|
||||
(" Example \n\t Domain \r\n" (Some "Example Domain"))
|
||||
;; A no-break space.
|
||||
((list->string (list #\R #\x00A0 #\s)) (Some "R s"))
|
||||
("" None)
|
||||
(" \n\t " None))
|
||||
(check (= (clean-title text) wanted)))
|
||||
|
||||
(deftest "a long title is cut at 300 characters"
|
||||
(check (= (clean-title (repeat #\a 400)) (Some (repeat #\a 300))))
|
||||
;; Characters, not UTF-16 units: each of these is two units.
|
||||
(def (Some cut) (clean-title (repeat #\x1F600 301)) :leave-with (check-fail "no title"))
|
||||
(check (= (string-count cut) 300))
|
||||
(check (= cut (repeat #\x1F600 300)))
|
||||
;; The space at the cut is trimmed.
|
||||
(check (= (clean-title (str (repeat #\a 299) " b")) (Some (repeat #\a 299)))))
|
||||
|
||||
(deftest "make-bookmark and bookmark-with-title clean the title"
|
||||
(def (Ok b) (make-bookmark "https://example.org/" #:title (Some " Example\nDomain "))
|
||||
:leave-with (check-fail "make-bookmark refused a good address"))
|
||||
(check (= (.title b) (Some "Example Domain")))
|
||||
(def (Ok untitled) (make-bookmark "https://example.org/") :leave-with (check-fail "refused"))
|
||||
(check (= (.title untitled) None))
|
||||
(def (Ok blank) (make-bookmark "https://example.org/" #:title (Some " ")) :leave-with (check-fail "refused"))
|
||||
(check (= (.title blank) None))
|
||||
(check (= (.title (bookmark-with-title example-bookmark (Some "\tNew title"))) (Some "New title")))
|
||||
(check (= (.title (bookmark-with-title example-bookmark (Some ""))) None))
|
||||
(check (= (.title (bookmark-with-title example-bookmark None)) None)))
|
||||
|
||||
;; ---- JSON of an entry ------------------------------------------------------------
|
||||
|
||||
(def example-json
|
||||
(str "{\"id\":\"0b9a2f0e-6a3c-4d7e-9f10-1a2b3c4d5e6f\","
|
||||
"\"stamp\":\"" stamp-a-text "\","
|
||||
"\"url\":\"https://example.org/\","
|
||||
"\"title\":\"Example Domain\","
|
||||
"\"added\":\"2026-11-11T09:12:00Z\","
|
||||
"\"tags\":[\"async\",\"rust\"],"
|
||||
"\"archive\":\"https://web.archive.org/web/20261111091200/https://example.org/\"}"))
|
||||
|
||||
(deftest "an entry as JSON"
|
||||
(check (= (json->string (entry->json example-entry)) example-json)))
|
||||
|
||||
(deftest "an entry read from JSON"
|
||||
(check (= (parse-entry example-json) (Ok example-entry))))
|
||||
|
||||
(deftest "a deleted entry"
|
||||
(def gone (deleted-entry (stamp-at 1762852320000L 2 phone) id-a))
|
||||
(def text (json->string (entry->json gone)))
|
||||
(check (= text (str "{\"id\":\"0b9a2f0e-6a3c-4d7e-9f10-1a2b3c4d5e6f\",\"stamp\":\"" stamp-a-text
|
||||
"\",\"deleted\":true}")))
|
||||
(check (= (parse-entry text) (Ok gone)))
|
||||
;; The fields of a deleted bookmark are not read.
|
||||
(check (= (parse-entry (str "{\"id\":\"0b9a2f0e-6a3c-4d7e-9f10-1a2b3c4d5e6f\",\"stamp\":\"" stamp-a-text
|
||||
"\",\"deleted\":true,\"url\":3}"))
|
||||
(Ok gone))))
|
||||
|
||||
(deftest "tags and the archive link can be left out"
|
||||
(def r (parse-entry (str "{\"id\":\"0b9a2f0e-6a3c-4d7e-9f10-1a2b3c4d5e6f\",\"stamp\":\"" stamp-a-text
|
||||
"\",\"url\":\"https://example.org/\",\"added\":\"2026-11-11T10:12:00+01:00\","
|
||||
"\"archive\":null,\"deleted\":false}")))
|
||||
(def (Ok e) r :leave-with (check-fail (error-of r)))
|
||||
(def (Live b) (.state e) :leave-with (check-fail "not live"))
|
||||
(check (= (.tags b) []))
|
||||
(check (= (.archive b) None))
|
||||
(check (= (.added b) (at "2026-11-11T09:12:00Z"))))
|
||||
|
||||
(deftest "tags are read as a set"
|
||||
(def r (parse-entry (str "{\"id\":\"0b9a2f0e-6a3c-4d7e-9f10-1a2b3c4d5e6f\",\"stamp\":\"" stamp-a-text
|
||||
"\",\"url\":\"https://example.org/\",\"added\":\"2026-11-11T09:12:00Z\","
|
||||
"\"tags\":[\"rust\",\"async\",\"rust\"]}")))
|
||||
(def (Ok e) r :leave-with (check-fail (error-of r)))
|
||||
(def (Live b) (.state e) :leave-with (check-fail "not live"))
|
||||
(check (= (.tags b) ["async" "rust"])))
|
||||
|
||||
(deftest "fields from a newer version are kept, in order, after the known ones"
|
||||
(def text (str "{\"rating\":4,\"id\":\"0b9a2f0e-6a3c-4d7e-9f10-1a2b3c4d5e6f\","
|
||||
"\"stamp\":\"" stamp-a-text "\",\"url\":\"https://example.org/\","
|
||||
"\"added\":\"2026-11-11T09:12:00Z\",\"x-visits\":[1,2],\"note\":{\"text\":\"hi\"}}"))
|
||||
(def r (parse-entry text))
|
||||
(def (Ok e) r :leave-with (check-fail (error-of r)))
|
||||
(check (= (vec-map fst (.extra e)) ["rating" "x-visits" "note"]))
|
||||
(check (= (json->string (entry->json e))
|
||||
(str "{\"id\":\"0b9a2f0e-6a3c-4d7e-9f10-1a2b3c4d5e6f\",\"stamp\":\"" stamp-a-text "\","
|
||||
"\"url\":\"https://example.org/\",\"added\":\"2026-11-11T09:12:00Z\",\"tags\":[],"
|
||||
"\"rating\":4,\"x-visits\":[1,2],\"note\":{\"text\":\"hi\"}}"))))
|
||||
|
||||
(deftest "a title can be left out, or null, and is read cleaned"
|
||||
(: (-> string (Option string)))
|
||||
(defun (title-of field)
|
||||
(match (parse-entry (str "{\"id\":\"0b9a2f0e-6a3c-4d7e-9f10-1a2b3c4d5e6f\",\"stamp\":\"" stamp-a-text
|
||||
"\",\"url\":\"https://example.org/\"," field "\"added\":\"2026-11-11T09:12:00Z\"}"))
|
||||
((Ok e) (match (.state e) ((Live b) (.title b)) ((Deleted _) (Some "deleted"))))
|
||||
((Err why) (Some (str "Err: " why)))))
|
||||
(check (= (title-of "") None))
|
||||
(check (= (title-of "\"title\":null,") None))
|
||||
(check (= (title-of "\"title\":\" \",") None))
|
||||
(check (= (title-of "\"title\":\" Example\\n Domain \",") (Some "Example Domain"))))
|
||||
|
||||
(deftest "a bookmark with no title writes no title field"
|
||||
(def untitled (live-entry (stamp-at 1762852320000L 2 phone) (bookmark-with-title example-bookmark None)))
|
||||
(def text (json->string (entry->json untitled)))
|
||||
(check (not (string-contains? text "title")))
|
||||
(check (= (parse-entry text) (Ok untitled))))
|
||||
|
||||
(: (-> string string))
|
||||
(defun (with-field field)
|
||||
(str "{\"id\":\"0b9a2f0e-6a3c-4d7e-9f10-1a2b3c4d5e6f\",\"stamp\":\"" stamp-a-text "\"," field "}"))
|
||||
|
||||
(deftest "what an entry must not be"
|
||||
#:cases ((text wanted)
|
||||
("[1]" "expected an object")
|
||||
("{\"stamp\":\"x\"}" "id: missing")
|
||||
("{\"id\":7}" "id: expected a string")
|
||||
("{\"id\":\"nope\"}" "id: not a uuid: nope")
|
||||
("{\"id\":\"0b9a2f0e-6a3c-4d7e-9f10-1a2b3c4d5e6f\",\"stamp\":\"soon\"}" "stamp: not a stamp: soon")
|
||||
((with-field "\"added\":\"2026-11-11T09:12:00Z\"") "url: missing")
|
||||
((with-field "\"url\":\"example.org\",\"added\":\"2026-11-11T09:12:00Z\"")
|
||||
"url: not an absolute URL: example.org")
|
||||
((with-field "\"url\":\"https://example.org/\"") "added: missing")
|
||||
((with-field "\"url\":\"https://example.org/\",\"added\":\"2026-11-11\"")
|
||||
"added: not an ISO 8601 date and time with an offset: 2026-11-11")
|
||||
((with-field "\"url\":\"https://example.org/\",\"added\":\"2026-11-11T09:12:00Z\",\"tags\":\"rust\"")
|
||||
"tags: expected an array of strings")
|
||||
((with-field "\"url\":\"https://example.org/\",\"added\":\"2026-11-11T09:12:00Z\",\"tags\":[\"a\",2]")
|
||||
"tags[1]: expected a string")
|
||||
((with-field "\"url\":\"https://example.org/\",\"added\":\"2026-11-11T09:12:00Z\",\"tags\":[\"\"]")
|
||||
"tags[0]: a tag cannot be empty")
|
||||
((with-field "\"url\":\"https://example.org/\",\"added\":\"2026-11-11T09:12:00Z\",\"archive\":1")
|
||||
"archive: expected a string or null")
|
||||
((with-field "\"url\":\"https://example.org/\",\"added\":\"2026-11-11T09:12:00Z\",\"archive\":\"x\"")
|
||||
"archive: not an absolute URL: x")
|
||||
((with-field "\"url\":\"https://example.org/\",\"added\":\"2026-11-11T09:12:00Z\",\"title\":[\"a\"]")
|
||||
"title: expected a string or null")
|
||||
((with-field "\"deleted\":\"yes\"") "deleted: expected true or false"))
|
||||
(check (= (error-of (parse-entry text)) wanted)))
|
||||
|
||||
;; ---- The document of a device -------------------------------------------------------
|
||||
|
||||
(def example-doc
|
||||
(DeviceDoc (device phone)
|
||||
(seen (map-set (map-empty) (uuid->string laptop) 41L))
|
||||
(entries [example-entry
|
||||
(deleted-entry (stamp-at 1762852321000L 0 laptop) id-b)])))
|
||||
|
||||
(deftest "a document reads back"
|
||||
(check (= (parse-device-doc (device-doc->string example-doc)) (Ok example-doc))))
|
||||
|
||||
(deftest "a document's records are in the order of their ids"
|
||||
(def reversed (record-set example-doc (entries (vec-reverse (.entries example-doc)))))
|
||||
(check (= (device-doc->string reversed) (device-doc->string example-doc))))
|
||||
|
||||
(deftest "a document as text"
|
||||
(check (= (device-doc->string (DeviceDoc (device phone) (seen (map-empty)) (entries [])))
|
||||
"{\"format\":1,\"device\":\"3f9c0d2a-1111-4222-8333-444455556666\",\"seen\":{},\"records\":[]}")))
|
||||
|
||||
(: (-> (Result string DeviceDoc) string))
|
||||
(defun (doc-error r)
|
||||
(match r
|
||||
((Ok _) "Ok")
|
||||
((Err why) why)))
|
||||
|
||||
(def doc-head "{\"format\":1,\"device\":\"3f9c0d2a-1111-4222-8333-444455556666\",")
|
||||
|
||||
(deftest "what a document must not be"
|
||||
#:cases ((text wanted)
|
||||
;; The message that the docs of parse-json give for this text.
|
||||
("[1, 2,]" "line 1, column 7: ']' does not begin a value")
|
||||
("[]" "expected an object")
|
||||
("{\"device\":\"x\"}" "format: missing")
|
||||
("{\"format\":2,\"records\":[]}" "format 2 is newer than this version reads (1)")
|
||||
("{\"format\":0}" "format 0 is not a format")
|
||||
("{\"format\":1,\"records\":[]}" "device: missing")
|
||||
((str doc-head "\"seen\":{}}") "records: missing")
|
||||
((str doc-head "\"records\":{}}") "records: expected an array")
|
||||
((str doc-head "\"seen\":[],\"records\":[]}") "seen: expected an object")
|
||||
((str doc-head "\"seen\":{\"x\":1},\"records\":[]}") "seen: not a uuid: x")
|
||||
((str doc-head "\"seen\":{\"77b2e40e-aaaa-4bbb-8ccc-ddddeeeeffff\":-1},\"records\":[]}")
|
||||
"seen.77b2e40e-aaaa-4bbb-8ccc-ddddeeeeffff: a revision cannot be negative")
|
||||
((str doc-head "\"records\":[" example-json ",{\"id\":3}]}") "records[1]: id: expected a string"))
|
||||
(check (= (doc-error (parse-device-doc text)) wanted)))
|
||||
|
||||
(deftest "the fields a document does not know are left out"
|
||||
(check (= (parse-device-doc (str doc-head "\"records\":[],\"later\":true}"))
|
||||
(Ok (DeviceDoc (device phone) (seen (map-empty)) (entries []))))))
|
||||
|
||||
;; ---- Merging --------------------------------------------------------------------
|
||||
|
||||
(deftest "the later stamp wins"
|
||||
(def older (live-entry (stamp-at 1000L 0 phone) example-bookmark))
|
||||
(def newer (live-entry (stamp-at 1000L 1 laptop) (bookmark-with-tags example-bookmark ["new"])))
|
||||
(check (= (map-try-ref (entries->map [older newer]) (uuid->string id-a)) (Some newer)))
|
||||
(check (= (map-try-ref (entries->map [newer older]) (uuid->string id-a)) (Some newer))))
|
||||
|
||||
(deftest "a delete wins over an older change, and a newer change wins over a delete"
|
||||
(def changed (live-entry (stamp-at 1000L 0 phone) example-bookmark))
|
||||
(def gone (deleted-entry (stamp-at 2000L 0 laptop) id-a))
|
||||
(def again (live-entry (stamp-at 3000L 0 phone) example-bookmark))
|
||||
(check (= (live-bookmarks (entries->map [changed gone])) []))
|
||||
(check (= (live-bookmarks (entries->map [gone changed])) []))
|
||||
(check (= (live-bookmarks (entries->map [gone again changed])) [example-bookmark])))
|
||||
|
||||
(deftest "the bookmarks, the newest first"
|
||||
(def b1 (record-set example-bookmark (id id-b) (added (at "2026-01-01T00:00:00Z"))))
|
||||
(def b2 (record-set example-bookmark (id id-c) (added (at "2026-06-01T00:00:00Z"))))
|
||||
(def es [(live-entry (stamp-at 1L 0 phone) b1) (live-entry (stamp-at 2L 0 phone) example-bookmark)
|
||||
(live-entry (stamp-at 3L 0 phone) b2)])
|
||||
(check (= (vec-map #(.id &) (live-bookmarks (entries->map es))) [id-a id-c id-b])))
|
||||
|
||||
(deftest "the clock of the entries is their latest stamp"
|
||||
(def es (entries->map [(live-entry (stamp-at 5L 3 phone) example-bookmark)
|
||||
(deleted-entry (stamp-at 9L 1 laptop) id-b)]))
|
||||
(check (= (entries-clock es) (Clock (last-ms 9L) (last-counter 1)))))
|
||||
|
||||
;; Few ids, devices and times, so that the generated entries collide often:
|
||||
;; the same id, the same time, and now and then the same stamp.
|
||||
(def gen-entry
|
||||
(gen-let ((id (gen-element (list id-a id-b id-c)))
|
||||
(ms (gen-long-range 0L 3L))
|
||||
(counter (gen-int-range 0 2))
|
||||
(device (gen-element (list phone laptop)))
|
||||
(deleted gen-bool)
|
||||
(tags (gen-element (list [] ["a"] ["a" "b"]))))
|
||||
(def s (stamp-at ms counter device))
|
||||
(if deleted
|
||||
(deleted-entry s id)
|
||||
(live-entry s (record-set example-bookmark (id id) (tags tags))))))
|
||||
|
||||
(def gen-entries (gen-vec gen-entry))
|
||||
|
||||
(deftest "merging is commutative"
|
||||
(for-all ((xs gen-entries) (ys gen-entries))
|
||||
(def a (entries->map xs))
|
||||
(def b (entries->map ys))
|
||||
(check (= (merge-maps a b) (merge-maps b a)))))
|
||||
|
||||
(deftest "merging is associative"
|
||||
(for-all ((xs gen-entries) (ys gen-entries) (zs gen-entries))
|
||||
(def a (entries->map xs))
|
||||
(def b (entries->map ys))
|
||||
(def c (entries->map zs))
|
||||
(check (= (merge-maps (merge-maps a b) c) (merge-maps a (merge-maps b c))))))
|
||||
|
||||
(deftest "merging twice changes nothing"
|
||||
(for-all ((xs gen-entries) (ys gen-entries))
|
||||
(def a (merge-maps (entries->map xs) (entries->map ys)))
|
||||
(check (= (merge-maps a a) a))
|
||||
(check (= (merge-maps a (entries->map ys)) a))))
|
||||
|
||||
(deftest "the order of the entries does not matter"
|
||||
(for-all ((xs gen-entries))
|
||||
(check (= (entries->map xs) (entries->map (vec-reverse xs))))))
|
||||
|
||||
(deftest "each id keeps its latest stamp, so a delete is never undone by an older change"
|
||||
(for-all ((xs gen-entries))
|
||||
(def merged (entries->map xs))
|
||||
(loop (:for e xs)
|
||||
(:do (match (map-try-ref merged (uuid->string (entry-id e)))
|
||||
((Some kept) (check (>= (stamp-compare (.stamp kept) (.stamp e)) 0)))
|
||||
(None (check-fail "an id was lost")))))))
|
||||
|
||||
(deftest "a merged document reads back as the same entries"
|
||||
(for-all ((xs gen-entries))
|
||||
(def entries (map-fold (fun (k e acc) (vec-add acc e)) [] (entries->map xs)))
|
||||
(def doc (DeviceDoc (device phone) (seen (map-empty)) (entries entries)))
|
||||
(match (parse-device-doc (device-doc->string doc))
|
||||
((Ok back) (check (= (entries->map (.entries back)) (entries->map entries))))
|
||||
((Err why) (check-fail why)))))
|
||||
|
||||
(run-tests)
|
||||
103
tests/draft.bjo
Normal file
103
tests/draft.bjo
Normal file
|
|
@ -0,0 +1,103 @@
|
|||
;; This Source Code Form is subject to the terms of the Mozilla Public
|
||||
;; License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
;; file, You can obtain one at http://mozilla.org/MPL/2.0/.
|
||||
|
||||
;; bjomarks/tests/draft.bjo — (bjomarks draft): the dialog of a bookmark,
|
||||
;; and the search.
|
||||
;;
|
||||
;; bjo run tests/draft.bjo
|
||||
|
||||
(import (std prelude))
|
||||
(import (std test))
|
||||
(import (std os))
|
||||
(import (bjomarks bookmark))
|
||||
(import (bjomarks keys))
|
||||
(import (bjomarks store))
|
||||
(import (bjomarks draft))
|
||||
|
||||
(def cheap (KeyCost (iterations 1) (memory-kib 8)))
|
||||
|
||||
;; A vault in a new folder, with the bookmarks of `urls`. Returns the vault
|
||||
;; and the folder, which the test deletes.
|
||||
(: (-> (Vec string) (Tuple Vault string)))
|
||||
(defun (vault-with urls)
|
||||
(def root (make-temp-directory #:prefix "bjomarks-draft-"))
|
||||
(def v0 (match (create-vault (folder-storage (path-combine root "shared")) (path-combine root "one") "pw" #:cost cheap)
|
||||
((Ok v) v)
|
||||
((Err _) (panic! "no vault"))))
|
||||
(Tuple (vec-fold (fun (url v)
|
||||
(match (vault-add v url #:tags ["web"])
|
||||
((Ok (Tuple v2 _)) v2)
|
||||
((Err why) (panic! why))))
|
||||
v0 urls)
|
||||
root))
|
||||
|
||||
(: (-> Vault Draft Vault))
|
||||
(defun (applied v d)
|
||||
(match (apply-draft v d)
|
||||
((Ok (Tuple v2 _)) v2)
|
||||
((Err why) (panic! why))))
|
||||
|
||||
(deftest "a new bookmark"
|
||||
(def (Tuple v root) (vault-with []))
|
||||
(def d (record-set empty-draft (url " https://example.org/a ") (title "A") (tags "x, y")))
|
||||
(def v2 (applied v d))
|
||||
(def b (vec-ref (vault-bookmarks v2) 0))
|
||||
(check (= (.url b) "https://example.org/a"))
|
||||
(check (= (.title b) (Some "A")))
|
||||
(check (= (.tags b) ["x" "y"]))
|
||||
(check (= (.archive b) None))
|
||||
(check-match (apply-draft v (record-set empty-draft (url "not an address"))) (Err _))
|
||||
(directory-delete-tree root))
|
||||
|
||||
(deftest "typing an address that a bookmark has loads it, and another address brings back what was typed"
|
||||
(def (Tuple v root) (vault-with ["https://example.org/a"]))
|
||||
(def typed (record-set empty-draft (title "Mine") (tags "t")))
|
||||
(def d1 (with-address v typed "https://example.org/a"))
|
||||
(check (some? (.editing d1)))
|
||||
(check (= (.problem d1) address-here))
|
||||
(check (= (.tags d1) "web"))
|
||||
(def d2 (with-address v d1 "https://example.org/b"))
|
||||
(check (none? (.editing d2)))
|
||||
(check (= (.title d2) "Mine"))
|
||||
(check (= (.tags d2) "t"))
|
||||
(check (= (.problem d2) ""))
|
||||
;; A dialog opened to edit a bookmark does not load another.
|
||||
(def edit (draft-of (vec-ref (vault-bookmarks v) 0)))
|
||||
(check (= (.editing (with-address v edit "https://example.org/a")) (.editing edit)))
|
||||
(directory-delete-tree root))
|
||||
|
||||
(deftest "an edit keeps the id, and checks the archive link"
|
||||
(def (Tuple v root) (vault-with ["https://example.org/a"]))
|
||||
(def b (vec-ref (vault-bookmarks v) 0))
|
||||
(def edit (draft-of b))
|
||||
(def d (record-set edit (title "Ay") (archive "https://web.archive.org/web/1/https://example.org/a")))
|
||||
(def v2 (applied v d))
|
||||
(def b2 (vec-ref (vault-bookmarks v2) 0))
|
||||
(check (= (.id b2) (.id b)))
|
||||
(check (= (.title b2) (Some "Ay")))
|
||||
(check (some? (.archive b2)))
|
||||
(check-match (apply-draft v (record-set edit (archive "no link"))) (Err _))
|
||||
(directory-delete-tree root))
|
||||
|
||||
(deftest "fetches: started, and their results taken only when the draft waits for them"
|
||||
(check (= (fetch-address (record-set empty-draft (url " example.org "))) (Some "https://example.org")))
|
||||
(check (= (fetch-address empty-draft) None))
|
||||
(check-match (start-title-fetch empty-draft 1) (Some (Err _)))
|
||||
(def (Some (Ok (Tuple d url))) (start-title-fetch (record-set empty-draft (url "example.org")) 3)
|
||||
:leave-with (check #f))
|
||||
(check (= url "https://example.org"))
|
||||
(check (= (.fetching d) (Some 3)))
|
||||
(check (none? (start-title-fetch d 4)))
|
||||
(check (= (.title (with-title-fetched d 3 (Ok (Ok "Example")))) "Example"))
|
||||
(check (= (.title (with-title-fetched d 2 (Ok (Ok "Old")))) ""))
|
||||
(check (= (.problem (with-title-fetched d 3 (Ok (Err "timed out")))) "No title: timed out."))
|
||||
(def (Some (Ok (Tuple a _))) (start-archive-fetch d 5)
|
||||
:leave-with (check #f))
|
||||
(check (= (.archive (with-archive-fetched a 5 (Ok (Ok "https://web.archive.org/x")))) "https://web.archive.org/x"))
|
||||
(check (= (.archive (with-archive-fetched a 6 (Ok (Ok "https://web.archive.org/y")))) "")))
|
||||
|
||||
(deftest "tags as typed"
|
||||
(check (= (split-tags "a, b,,c d") ["a" "b" "c" "d"])))
|
||||
|
||||
(run-tests)
|
||||
135
tests/duplicates.bjo
Normal file
135
tests/duplicates.bjo
Normal file
|
|
@ -0,0 +1,135 @@
|
|||
;; This Source Code Form is subject to the terms of the Mozilla Public
|
||||
;; License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
;; file, You can obtain one at http://mozilla.org/MPL/2.0/.
|
||||
|
||||
;; bjomarks/tests/duplicates.bjo — (bjomarks duplicates): two devices that
|
||||
;; add one page before they sync, in folders of the temp directory.
|
||||
;;
|
||||
;; bjo run tests/duplicates.bjo
|
||||
|
||||
(import (std prelude))
|
||||
(import (std test))
|
||||
(import (std os))
|
||||
(import (std datetime))
|
||||
(import (std uuid))
|
||||
(import (bjomarks bookmark))
|
||||
(import (bjomarks keys))
|
||||
(import (bjomarks store))
|
||||
(import (bjomarks duplicates))
|
||||
|
||||
(def cheap (KeyCost (iterations 1) (memory-kib 8)))
|
||||
|
||||
(: (-> string Instant))
|
||||
(defun (instant text)
|
||||
(match (iso8601->instant text)
|
||||
((Some i) i)
|
||||
(None (panic! (str "not an instant: " text)))))
|
||||
|
||||
(: (-> (Result StoreError Vault) Vault))
|
||||
(defun (must r)
|
||||
(match r
|
||||
((Ok v) v)
|
||||
((Err _) (panic! "no vault"))))
|
||||
|
||||
;; Two devices of one vault, in a new folder.
|
||||
(: (-> (Tuple string Vault Vault)))
|
||||
(defun (two-devices)
|
||||
(def root (make-temp-directory #:prefix "bjomarks-dup-"))
|
||||
(def shared (path-combine root "shared"))
|
||||
(def one (must (create-vault (folder-storage shared) (path-combine root "one") "pw" #:cost cheap)))
|
||||
(def two (match (join-vault (folder-storage shared) (path-combine root "two") "pw")
|
||||
((Ok (Tuple v _)) v)
|
||||
((Err _) (panic! "no join"))))
|
||||
(Tuple root one two))
|
||||
|
||||
(: (-> Vault string (Option string) (Vec string) string (Option string) Vault))
|
||||
(defun (add-page v url title tags when archive)
|
||||
(match (vault-add v url #:title title #:tags tags #:added (instant when) #:archive archive)
|
||||
((Ok (Tuple v2 _)) v2)
|
||||
((Err why) (panic! why))))
|
||||
|
||||
(: (-> Vault Vault))
|
||||
(defun (synced v) (fst (vault-sync v)))
|
||||
|
||||
;; Both devices see the bookmarks of both.
|
||||
(: (-> Vault Vault (Tuple Vault Vault)))
|
||||
(defun (exchange a b)
|
||||
(def a2 (synced a))
|
||||
(def b2 (synced b))
|
||||
(Tuple (synced a2) b2))
|
||||
|
||||
(: (-> Vault string (Vec Bookmark)))
|
||||
(defun (of-page v url) (vec-filter (fun (b) (= (.url b) url)) (vault-bookmarks v)))
|
||||
|
||||
(deftest "one page from two devices, with one title, becomes one bookmark"
|
||||
(def (Tuple root one0 two0) (two-devices))
|
||||
(def one1 (add-page one0 "https://example.org/a" (Some "A page") ["x" "web"] "2026-01-01T10:00:00Z" None))
|
||||
(def two1 (add-page two0 "https://example.org/a" None ["y" "web"] "2025-06-01T10:00:00Z"
|
||||
(Some "https://web.archive.org/a")))
|
||||
(def two2 (add-page two1 "https://example.org/b" (Some "B") [] "2026-02-01T10:00:00Z" None))
|
||||
(def (Tuple one2 two3) (exchange one1 two2))
|
||||
(check (= (vec-length (of-page one2 "https://example.org/a")) 2))
|
||||
(def (Tuple one3 asked) (vault-join-duplicates one2))
|
||||
(check (vec-empty? asked))
|
||||
(def pages (of-page one3 "https://example.org/a"))
|
||||
(check (= (vec-length pages) 1))
|
||||
(def b (vec-ref pages 0))
|
||||
(check (= (.title b) (Some "A page")))
|
||||
(check (= (.tags b) ["web" "x" "y"]))
|
||||
(check (= (instant->unix-milliseconds (.added b)) (instant->unix-milliseconds (instant "2025-06-01T10:00:00Z"))))
|
||||
(check (= (.archive b) (Some "https://web.archive.org/a")))
|
||||
(check (= (vec-length (vault-bookmarks one3)) 2))
|
||||
;; Joining again changes nothing.
|
||||
(def (Tuple one4 again) (vault-join-duplicates one3))
|
||||
(check (vec-empty? again))
|
||||
(check (not (vault-dirty? (vault-save one4))))
|
||||
(check (= (vault-revision (vault-save one4)) (vault-revision (vault-save one3))))
|
||||
;; The other device joins it too, the same way, and they agree.
|
||||
(def (Tuple two4 _) (vault-join-duplicates two3))
|
||||
(def (Tuple one5 two5) (exchange (vault-save one4) (vault-save two4)))
|
||||
(def a1 (of-page one5 "https://example.org/a"))
|
||||
(def a2 (of-page two5 "https://example.org/a"))
|
||||
(check (= (vec-length a1) 1))
|
||||
(check (= (vec-length a2) 1))
|
||||
(check (= (.id (vec-ref a1 0)) (.id (vec-ref a2 0))))
|
||||
(check (= (.tags (vec-ref a1 0)) (.tags (vec-ref a2 0))))
|
||||
(directory-delete-tree root))
|
||||
|
||||
(deftest "different titles are asked, and the one chosen is kept"
|
||||
(def (Tuple root one0 two0) (two-devices))
|
||||
(def one1 (add-page one0 "https://example.org/a" (Some "First") ["x"] "2026-01-01T10:00:00Z" None))
|
||||
(def two1 (add-page two0 "https://example.org/a" (Some "Second") ["y"] "2026-01-02T10:00:00Z" None))
|
||||
(def (Tuple one2 _) (exchange one1 two1))
|
||||
(def (Tuple one3 asked) (vault-join-duplicates one2))
|
||||
(check (= (vec-length asked) 1))
|
||||
(def d (vec-ref asked 0))
|
||||
(check (= (duplicate-url d) "https://example.org/a"))
|
||||
(check (= (duplicate-titles d) ["First" "Second"]))
|
||||
(check (= (vec-length (duplicate-ids d)) 2))
|
||||
;; Both stay, with the tags of both.
|
||||
(def pages (of-page one3 "https://example.org/a"))
|
||||
(check (= (vec-length pages) 2))
|
||||
(check (= (vec-length (vec-filter (fun (b) (= (.tags b) ["x" "y"])) pages)) 2))
|
||||
;; Asked again, until a title is chosen.
|
||||
(def (Tuple one4 again) (vault-join-duplicates one3))
|
||||
(check (= (vec-length again) 1))
|
||||
(def one5 (vault-choose-title one4 "https://example.org/a" (Some "Second")))
|
||||
(def kept (of-page one5 "https://example.org/a"))
|
||||
(check (= (vec-length kept) 1))
|
||||
(check (= (.title (vec-ref kept 0)) (Some "Second")))
|
||||
(check (= (.tags (vec-ref kept 0)) ["x" "y"]))
|
||||
(def (Tuple _ none) (vault-join-duplicates one5))
|
||||
(check (vec-empty? none))
|
||||
(directory-delete-tree root))
|
||||
|
||||
(deftest "a page with one bookmark is left alone"
|
||||
(def (Tuple root one0 _) (two-devices))
|
||||
(def one1 (vault-save (add-page one0 "https://example.org/a" (Some "A") [] "2026-01-01T10:00:00Z" None)))
|
||||
(def one2 (add-page one1 "https://example.org/a/" (Some "A") [] "2026-01-01T10:00:00Z" None))
|
||||
(def (Tuple one3 asked) (vault-join-duplicates one2))
|
||||
(check (vec-empty? asked))
|
||||
(check (= (vec-length (vault-bookmarks one3)) 2))
|
||||
(check (= (vault-choose-title one3 "https://example.org/a" (Some "B")) one3))
|
||||
(directory-delete-tree root))
|
||||
|
||||
(run-tests)
|
||||
181
tests/import.bjo
Normal file
181
tests/import.bjo
Normal file
|
|
@ -0,0 +1,181 @@
|
|||
;; This Source Code Form is subject to the terms of the Mozilla Public
|
||||
;; License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
;; file, You can obtain one at http://mozilla.org/MPL/2.0/.
|
||||
|
||||
;; bjomarks/tests/import.bjo — (bjomarks import): Firefox's JSON backup, and
|
||||
;; an import into a vault.
|
||||
;;
|
||||
;; bjo run tests/import.bjo
|
||||
;;
|
||||
;; The backup here is made up, in the shape Firefox writes: the fields of
|
||||
;; each node, the four top folders with a "root" field, and dates in
|
||||
;; microseconds.
|
||||
|
||||
(import (std prelude))
|
||||
(import (std test))
|
||||
(import (std datetime))
|
||||
(import (std os))
|
||||
(import (bjomarks bookmark))
|
||||
(import (bjomarks keys))
|
||||
(import (bjomarks store))
|
||||
(import (bjomarks import))
|
||||
|
||||
(: (-> long Instant))
|
||||
(defun (at-seconds s)
|
||||
(match (unix-microseconds->instant (* s 1000000L))
|
||||
((Some i) i)
|
||||
(None (panic! "no instant"))))
|
||||
|
||||
;; The instant given to a bookmark with no date.
|
||||
(def fallback (at-seconds 1800000000L))
|
||||
|
||||
(def backup
|
||||
"""
|
||||
{"guid":"root________","title":"","index":0,"dateAdded":1500000000000000,"lastModified":1500000000000000,
|
||||
"id":1,"typeCode":2,"type":"text/x-moz-place-container","root":"placesRoot","children":[
|
||||
{"guid":"menu________","title":"menu","index":0,"dateAdded":1500000000000000,"lastModified":1500000000000000,
|
||||
"id":2,"typeCode":2,"type":"text/x-moz-place-container","root":"bookmarksMenuFolder","children":[
|
||||
{"guid":"folderA00001","title":" Rust Docs ","index":0,"dateAdded":1700000000000000,"lastModified":1700000000000000,
|
||||
"id":7,"typeCode":2,"type":"text/x-moz-place-container","children":[
|
||||
{"guid":"bookmark0001","title":"The Book","index":0,"dateAdded":1700000100000000,"lastModified":1700000100000000,
|
||||
"id":8,"typeCode":1,"type":"text/x-moz-place","uri":"https://doc.rust-lang.org/book/","tags":"Rust,Must Read"},
|
||||
{"guid":"folderB00001","title":"Async, Await","index":1,"dateAdded":1700000000000000,"lastModified":1700000000000000,
|
||||
"id":9,"typeCode":2,"type":"text/x-moz-place-container","children":[
|
||||
{"guid":"bookmark0002","title":"Async book","index":0,"dateAdded":1700000200000000,
|
||||
"lastModified":1700000200000000,"id":10,"typeCode":1,"type":"text/x-moz-place",
|
||||
"uri":"https://rust-lang.github.io/async-book/"}]}]},
|
||||
{"guid":"separator001","title":"","index":1,"dateAdded":1700000000000000,"lastModified":1700000000000000,
|
||||
"id":11,"typeCode":3,"type":"text/x-moz-place-separator"},
|
||||
{"guid":"bookmark0003","title":"Most Visited","index":2,"dateAdded":1700000000000000,
|
||||
"lastModified":1700000000000000,"id":12,"typeCode":1,"type":"text/x-moz-place",
|
||||
"uri":"place:sort=8&maxResults=10"},
|
||||
{"guid":"bookmark0004","title":"A bookmarklet","index":3,"dateAdded":1700000000000000,
|
||||
"lastModified":1700000000000000,"id":13,"typeCode":1,"type":"text/x-moz-place",
|
||||
"uri":"javascript:alert(1)","keyword":"js"},
|
||||
{"guid":"bookmark0005","title":"","index":4,"dateAdded":1700000300000000,"lastModified":1700000300000000,
|
||||
"id":14,"typeCode":1,"type":"text/x-moz-place","uri":" HTTPS://Example.org/Upper "}]},
|
||||
{"guid":"toolbar_____","title":"toolbar","index":1,"dateAdded":1500000000000000,"lastModified":1500000000000000,
|
||||
"id":3,"typeCode":2,"type":"text/x-moz-place-container","root":"toolbarFolder","children":[
|
||||
{"guid":"bookmark0006","title":"The Rust book, again","index":0,"dateAdded":1600000000000000,
|
||||
"lastModified":1600000000000000,"id":15,"typeCode":1,"type":"text/x-moz-place",
|
||||
"uri":"https://doc.rust-lang.org/book/","tags":"reading"}]},
|
||||
{"guid":"unfiled_____","title":"unfiled","index":3,"dateAdded":1500000000000000,"lastModified":1500000000000000,
|
||||
"id":5,"typeCode":2,"type":"text/x-moz-place-container","root":"unfiledBookmarksFolder","children":[
|
||||
{"guid":"bookmark0007","title":"No date","index":0,"id":16,"typeCode":1,"type":"text/x-moz-place",
|
||||
"uri":"http://example.com/"},
|
||||
{"guid":"bookmark0008","title":"Two hashes","index":1,"dateAdded":1700000400000000,"id":17,"typeCode":1,
|
||||
"type":"text/x-moz-place","uri":"https://example.org/app#/page#part"}]},
|
||||
{"guid":"mobile______","title":"mobile","index":4,"dateAdded":1500000000000000,"lastModified":1500000000000000,
|
||||
"id":6,"typeCode":2,"type":"text/x-moz-place-container","root":"mobileFolder","children":[]}]}
|
||||
""")
|
||||
|
||||
(: (-> FirefoxBackup))
|
||||
(defun (read-backup)
|
||||
(match (read-firefox-backup backup #:now fallback)
|
||||
((Ok b) b)
|
||||
((Err why) (panic! why))))
|
||||
|
||||
(: (-> string Imported))
|
||||
(defun (imported url)
|
||||
(def found (vec-filter (fun (i) (= (.url i) url)) (.bookmarks (read-backup))))
|
||||
(if (vec-empty? found) (panic! (str "not imported: " url)) (vec-ref found 0)))
|
||||
|
||||
(: (-> (Result string FirefoxBackup) string))
|
||||
(defun (error-of r)
|
||||
(match r
|
||||
((Ok _) "Ok")
|
||||
((Err why) why)))
|
||||
|
||||
;; ---- Tag names -----------------------------------------------------------------------
|
||||
|
||||
(deftest "a tag's name"
|
||||
#:cases ((text wanted)
|
||||
("Rust" (Some "rust"))
|
||||
(" Rust Docs " (Some "rust-docs"))
|
||||
("Async, Await" (Some "async-await"))
|
||||
("a\tb\nc" (Some "a-b-c"))
|
||||
(",lead,and,trail," (Some "lead-and-trail"))
|
||||
(" , " None)
|
||||
("" None))
|
||||
(check (= (tag-name text) wanted)))
|
||||
|
||||
;; ---- Reading a backup ----------------------------------------------------------------
|
||||
|
||||
(deftest "the bookmarks of a backup, one for each address, in the order found"
|
||||
(check (= (vec-map #(.url &) (.bookmarks (read-backup)))
|
||||
["https://doc.rust-lang.org/book/" "https://rust-lang.github.io/async-book/"
|
||||
"HTTPS://Example.org/Upper" "http://example.com/"])))
|
||||
|
||||
(deftest "addresses that are not http or https are counted and left out"
|
||||
(check (= (.not-web (read-backup)) 2)))
|
||||
|
||||
(deftest "an http address that is not a URL is left out, and named with the reason"
|
||||
(def invalid (.invalid (read-backup)))
|
||||
(check (= (vec-map fst invalid) ["https://example.org/app#/page#part"]))
|
||||
(check (vec-fold (fun (p ok) (and ok (string-contains? (snd p) "'#' is not allowed in the fragment"))) #t invalid)))
|
||||
|
||||
(deftest "folders of the user's are tags, at any depth; Firefox's top folders are not"
|
||||
(check (= (.tags (imported "https://rust-lang.github.io/async-book/")) ["async-await" "rust-docs"]))
|
||||
(check (= (.tags (imported "http://example.com/")) [])))
|
||||
|
||||
(deftest "Firefox's tags are tags, named as folders are"
|
||||
(check (vec-contains? (.tags (imported "https://doc.rust-lang.org/book/")) "must-read")))
|
||||
|
||||
(deftest "an address bookmarked twice is one bookmark"
|
||||
(def book (imported "https://doc.rust-lang.org/book/"))
|
||||
(check (= (.copies (read-backup)) 1))
|
||||
(check (= (.tags book) ["must-read" "reading" "rust" "rust-docs"]))
|
||||
(check (= (.title book) (Some "The Book")))
|
||||
(check (= (.added book) (at-seconds 1600000000L))))
|
||||
|
||||
(deftest "the date is Firefox's, in microseconds, and a bookmark with none gets now"
|
||||
(check (= (.added (imported "https://rust-lang.github.io/async-book/")) (at-seconds 1700000200L)))
|
||||
(check (= (.added (imported "http://example.com/")) fallback)))
|
||||
|
||||
(deftest "an empty title is no title"
|
||||
(check (= (.title (imported "HTTPS://Example.org/Upper")) None))
|
||||
(check (= (.title (imported "https://rust-lang.github.io/async-book/")) (Some "Async book"))))
|
||||
|
||||
(deftest "what is not a backup"
|
||||
#:cases ((text wanted)
|
||||
("<!DOCTYPE NETSCAPE-Bookmark-file-1>\n<TITLE>Bookmarks</TITLE>"
|
||||
(str "this is Firefox's HTML export, and bjomarks reads the JSON backup: in Firefox's "
|
||||
"Library window, choose Import and Backup, then Backup…"))
|
||||
("[1, 2]" "not a Firefox bookmark backup: it is not an object")
|
||||
("{\"a\": 1}" "not a Firefox bookmark backup: it has no top folder"))
|
||||
(check (= (error-of (read-firefox-backup text)) wanted)))
|
||||
|
||||
(deftest "text that is not JSON"
|
||||
(check (string-starts-with? (error-of (read-firefox-backup "{\"type\": ")) "not JSON: ")))
|
||||
|
||||
;; ---- Into a vault --------------------------------------------------------------------
|
||||
|
||||
(deftest "an import adds the addresses that the vault does not have, and changes no other"
|
||||
(def root (make-temp-directory #:prefix "bjomarks-import-"))
|
||||
(def made (match (create-vault (folder-storage (path-combine root "shared")) (path-combine root "local") "pw"
|
||||
#:cost (KeyCost (iterations 1) (memory-kib 8)))
|
||||
((Ok v) v)
|
||||
((Err _) (panic! "the vault was not made"))))
|
||||
(def (Ok (Tuple v0 mine)) (vault-add made "https://doc.rust-lang.org/book/" #:tags ["mine"])
|
||||
:leave-with (check-fail "vault-add refused"))
|
||||
(def (Tuple v1 report) (vault-import v0 (.bookmarks (read-backup))))
|
||||
(check (= (.added report) 3))
|
||||
(check (= (.already report) 1))
|
||||
(check (= (.refused report) []))
|
||||
(check (= (vec-length (vault-bookmarks v1)) 4))
|
||||
(check (= (match (vault-find v1 (.id mine)) ((Some b) (.tags b)) (None [])) ["mine"]))
|
||||
(def async (vec-filter (fun (b) (= (.url b) "https://rust-lang.github.io/async-book/")) (vault-bookmarks v1)))
|
||||
(check (= (vec-map #(.tags &) async) [["async-await" "rust-docs"]]))
|
||||
(check (= (vec-map #(.title &) async) [(Some "Async book")]))
|
||||
(check (= (vec-map #(.added &) async) [(at-seconds 1700000200L)]))
|
||||
;; The same backup again adds nothing.
|
||||
(def (Tuple v2 again) (vault-import v1 (.bookmarks (read-backup))))
|
||||
(check (= (.added again) 0))
|
||||
(check (= (.already again) 4))
|
||||
(check (= (vec-length (vault-bookmarks v2)) 4))
|
||||
;; And it is saved as any change is.
|
||||
(check (vault-dirty? v2))
|
||||
(vault-close (fst (vault-sync v2)))
|
||||
(directory-delete-tree root))
|
||||
|
||||
(run-tests)
|
||||
166
tests/keys.bjo
Normal file
166
tests/keys.bjo
Normal file
|
|
@ -0,0 +1,166 @@
|
|||
;; This Source Code Form is subject to the terms of the Mozilla Public
|
||||
;; License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
;; file, You can obtain one at http://mozilla.org/MPL/2.0/.
|
||||
|
||||
;; bjomarks/tests/keys.bjo — (bjomarks keys): keys files that open, and the
|
||||
;; changes to one that must make it fail.
|
||||
;;
|
||||
;; bjo run tests/keys.bjo
|
||||
;;
|
||||
;; The tests use a cost of 1 iteration over 8 KiB, so that they are quick.
|
||||
|
||||
(import (std prelude))
|
||||
(import (std test))
|
||||
(import (std uuid))
|
||||
(import (bjosodium core))
|
||||
(import (bjomarks binary))
|
||||
(import (bjomarks keys))
|
||||
|
||||
(def cheap (KeyCost (iterations 1) (memory-kib 8)))
|
||||
|
||||
(: (-> (Result KeysError Unlocked) string))
|
||||
(defun (outcome r)
|
||||
(match r
|
||||
((Ok _) "Ok")
|
||||
((Err WrongPassword) "WrongPassword")
|
||||
((Err (BadKeys why)) why)))
|
||||
|
||||
(: (-> (Array byte) (Array byte)))
|
||||
(defun (copy-of a) (get-bytes a 0 (array-length a)))
|
||||
|
||||
;; A copy of `a` with bit 0 of byte `at` changed.
|
||||
(: (-> (Array byte) int (Array byte)))
|
||||
(defun (flipped a at)
|
||||
(def b (copy-of a))
|
||||
(put-u8! b at (bitwise-xor (get-u8 b at) 1))
|
||||
b)
|
||||
|
||||
(: (-> (Array byte) int int (Array byte)))
|
||||
(defun (with-u8 a at v)
|
||||
(def b (copy-of a))
|
||||
(put-u8! b at v)
|
||||
b)
|
||||
|
||||
(: (-> (Array byte) int int (Array byte)))
|
||||
(defun (with-u32 a at v)
|
||||
(def b (copy-of a))
|
||||
(put-u32! b at v)
|
||||
b)
|
||||
|
||||
(deftest "a new vault opens with its password"
|
||||
(def (Tuple file made) (make-keys "hunter2" #:cost cheap))
|
||||
(def (Ok opened) (unlock-keys file "hunter2") :leave-with (check-fail "it did not open"))
|
||||
(check (= (.vault-id opened) (.vault-id made)))
|
||||
(check (= (.key-id opened) 1))
|
||||
(check (bytes=? (.dek opened) (.dek made)))
|
||||
(check (= (array-length (.dek made)) 32))
|
||||
(check (= (keys-vault-id file) (Ok (.vault-id made)))))
|
||||
|
||||
(deftest "each cipher wraps the key"
|
||||
#:cases ((cipher length)
|
||||
(Aegis256 150)
|
||||
(XChaCha20Poly1305 126))
|
||||
(def (Tuple file _made) (make-keys "hunter2" #:cost cheap #:cipher cipher))
|
||||
(check (= (array-length file) length))
|
||||
(check (= (get-u8 file 53) (cipher->code cipher)))
|
||||
(check (= (outcome (unlock-keys file "hunter2")) "Ok"))
|
||||
(check (= (outcome (unlock-keys file "hunter3")) "WrongPassword")))
|
||||
|
||||
(deftest "a wrong password"
|
||||
(def (Tuple file _made) (make-keys "hunter2" #:cost cheap))
|
||||
(check (= (outcome (unlock-keys file "")) "WrongPassword"))
|
||||
(check (= (outcome (unlock-keys file "Hunter2")) "WrongPassword")))
|
||||
|
||||
(deftest "two vaults have their own ids and keys"
|
||||
(def (Tuple _f1 a) (make-keys "pw" #:cost cheap))
|
||||
(def (Tuple _f2 b) (make-keys "pw" #:cost cheap))
|
||||
(check (not (= (.vault-id a) (.vault-id b))))
|
||||
(check (not (bytes=? (.dek a) (.dek b)))))
|
||||
|
||||
(deftest "a new password keeps the vault and its key"
|
||||
(def (Tuple old made) (make-keys "old password" #:cost cheap))
|
||||
(def new (wrap-keys (.vault-id made) (.key-id made) (.dek made) "new password" #:cost cheap))
|
||||
(check (= (outcome (unlock-keys new "old password")) "WrongPassword"))
|
||||
(def (Ok opened) (unlock-keys new "new password") :leave-with (check-fail "it did not open"))
|
||||
(check (bytes=? (.dek opened) (.dek made)))
|
||||
(check (= (.vault-id opened) (.vault-id made)))
|
||||
(check (= (outcome (unlock-keys old "old password")) "Ok")))
|
||||
|
||||
;; The offsets of the fields of the one slot, which starts at 23.
|
||||
(deftest "a change to a field that the slot's tag covers"
|
||||
#:cases ((what at)
|
||||
("the vault id" 6)
|
||||
("the vault id's last byte" 21)
|
||||
("the key id" 27)
|
||||
("the memory" 36)
|
||||
("the salt" 37)
|
||||
("the nonce" 54)
|
||||
("the wrapped key" 90)
|
||||
("the tag" 149))
|
||||
(def (Tuple file _made) (make-keys "hunter2" #:cost cheap #:cipher Aegis256))
|
||||
(check (= (outcome (unlock-keys (flipped file at) "hunter2")) "WrongPassword")))
|
||||
|
||||
(deftest "another cost in bounds does not open the slot"
|
||||
(def (Tuple file _made) (make-keys "hunter2" #:cost cheap #:cipher Aegis256))
|
||||
(check (= (outcome (unlock-keys (with-u32 file 29 2) "hunter2")) "WrongPassword")))
|
||||
|
||||
(deftest "what a keys file must not be"
|
||||
(def (Tuple file _made) (make-keys "hunter2" #:cost cheap #:cipher Aegis256))
|
||||
(check (= (outcome (unlock-keys (make-array 0) "hunter2")) "too short for a keys file"))
|
||||
(check (= (outcome (unlock-keys (flipped file 0) "hunter2")) "not a keys file"))
|
||||
(check (= (outcome (unlock-keys (with-u8 file 5 2) "hunter2")) "keys file version 2 is not version 1"))
|
||||
(check (= (outcome (unlock-keys (with-u8 file 22 2) "hunter2")) "a slot is cut short"))
|
||||
(check (= (outcome (unlock-keys (with-u8 file 22 0) "hunter2")) "bytes after the last slot"))
|
||||
(check (= (outcome (unlock-keys (get-bytes file 0 (- (array-length file) 1)) "hunter2")) "a slot is cut short"))
|
||||
(check (= (outcome (unlock-keys (bytes-concat file (make-array 1)) "hunter2")) "bytes after the last slot"))
|
||||
(check (= (outcome (unlock-keys (with-u8 file 53 9) "hunter2")) "unknown cipher 9"))
|
||||
(check (= (outcome (unlock-keys (with-u8 file 23 2) "hunter2")) "no password slot"))
|
||||
(check (= (outcome (unlock-keys (with-u8 file 28 2) "hunter2")) "no password slot"))
|
||||
(check (= (outcome (unlock-keys (with-u32 file 29 1000) "hunter2")) "a slot asks for 1000 iterations"))
|
||||
(check (= (outcome (unlock-keys (with-u32 file 29 0) "hunter2")) "a slot asks for 0 iterations"))
|
||||
(check (= (outcome (unlock-keys (with-u32 file 33 4) "hunter2")) "a slot asks for 4 KiB"))
|
||||
(check (= (outcome (unlock-keys (with-u32 file 33 -1) "hunter2")) "a slot asks for -1 KiB"))
|
||||
;; At most 1 GiB: a file of an attacker cannot make a phone use more.
|
||||
(check (= (outcome (unlock-keys (with-u32 file 33 1048577) "hunter2")) "a slot asks for 1048577 KiB")))
|
||||
|
||||
(deftest "the vault id needs no password"
|
||||
(def (Tuple file made) (make-keys "hunter2" #:cost cheap))
|
||||
(check (= (keys-vault-id file) (Ok (.vault-id made))))
|
||||
(check-match (keys-vault-id (flipped file 1)) (Err (BadKeys _))))
|
||||
|
||||
;; ---- A new key for a new password ------------------------------------------
|
||||
|
||||
(deftest "a new password comes with a new key, and keeps the earlier one"
|
||||
(def (Tuple old made) (make-keys "old password" #:cost cheap))
|
||||
(def (Tuple new rotated) (new-keys made "new password" #:cost cheap))
|
||||
(check (= (.vault-id rotated) (.vault-id made)))
|
||||
(check (not (= (.key-id rotated) (.key-id made))))
|
||||
(check (not (bytes=? (.dek rotated) (.dek made))))
|
||||
;; The new file opens with the new password, and gives the earlier key.
|
||||
(def (Ok opened) (unlock-keys new "new password") :leave-with (check-fail "it did not open"))
|
||||
(check (= (.key-id opened) (.key-id rotated)))
|
||||
(check (bytes=? (.dek opened) (.dek rotated)))
|
||||
(check (= (vec-map fst (.earlier opened)) [1]))
|
||||
(check (bytes=? (snd (vec-ref (.earlier opened) 0)) (.dek made)))
|
||||
(check (= (outcome (unlock-keys new "old password")) "WrongPassword"))
|
||||
;; The old file and the old password give the old key only.
|
||||
(def (Ok was) (unlock-keys old "old password") :leave-with (check-fail "the old file did not open"))
|
||||
(check (= (.key-id was) 1))
|
||||
(check (vec-empty? (.earlier was)))
|
||||
;; The ids show without a password.
|
||||
(check (= (keys-key-ids new) (Ok (KeyIds (current (.key-id rotated)) (earlier-ids [1])))))
|
||||
(check (= (keys-key-ids old) (Ok (KeyIds (current 1) (earlier-ids [])))))
|
||||
;; A second change keeps both, the latest first.
|
||||
(def (Tuple third again) (new-keys opened "third" #:cost cheap))
|
||||
(def (Ok opened3) (unlock-keys third "third") :leave-with (check-fail "the third did not open"))
|
||||
(check (= (vec-map fst (.earlier opened3)) [(.key-id rotated) 1]))
|
||||
(check (= (.key-id opened3) (.key-id again))))
|
||||
|
||||
(deftest "an earlier key that was changed does not open"
|
||||
(def (Tuple _old made) (make-keys "pw" #:cost cheap #:cipher Aegis256))
|
||||
(def (Tuple new _rotated) (new-keys made "pw2" #:cost cheap #:cipher Aegis256))
|
||||
;; The second slot starts at 23 + 127; its wrapped key at 23 + 127 + 63.
|
||||
(check (= (outcome (unlock-keys (flipped new (+ 150 70)) "pw2")) "the earlier key 1 does not open"))
|
||||
(check (= (outcome (unlock-keys (with-u32 new 151 7) "pw2")) "the earlier key 7 does not open")))
|
||||
|
||||
(run-tests)
|
||||
133
tests/search.bjo
Normal file
133
tests/search.bjo
Normal file
|
|
@ -0,0 +1,133 @@
|
|||
;; This Source Code Form is subject to the terms of the Mozilla Public
|
||||
;; License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
;; file, You can obtain one at http://mozilla.org/MPL/2.0/.
|
||||
|
||||
;; bjomarks/tests/search.bjo — (bjomarks search), on a vault in the temp
|
||||
;; directory.
|
||||
;;
|
||||
;; bjo run tests/search.bjo
|
||||
|
||||
(import (std prelude))
|
||||
(import (std test))
|
||||
(import (std os))
|
||||
(import (std datetime))
|
||||
(import (bjomarks bookmark))
|
||||
(import (bjomarks keys))
|
||||
(import (bjomarks store))
|
||||
(import (bjomarks search))
|
||||
|
||||
(def cheap (KeyCost (iterations 1) (memory-kib 8)))
|
||||
|
||||
(: (-> string Instant))
|
||||
(defun (instant text)
|
||||
(match (iso8601->instant text)
|
||||
((Some i) i)
|
||||
(None (panic! (str "not an instant: " text)))))
|
||||
|
||||
(: (-> Vault string string (Vec string) string Vault))
|
||||
(defun (add-page v url title tags when)
|
||||
(match (vault-add v url #:title (if (string-empty? title) None (Some title)) #:tags tags
|
||||
#:added (instant (str when "T12:00:00Z")))
|
||||
((Ok (Tuple v2 _)) v2)
|
||||
((Err why) (panic! why))))
|
||||
|
||||
;; Bookmarks, the newest last.
|
||||
(: (-> (Tuple string Vault)))
|
||||
(defun (example)
|
||||
(def root (make-temp-directory #:prefix "bjomarks-search-"))
|
||||
(def v0 (match (create-vault (folder-storage (path-combine root "shared")) (path-combine root "here") "pw"
|
||||
#:cost cheap)
|
||||
((Ok v) v)
|
||||
((Err _) (panic! "no vault"))))
|
||||
(def v (vec-fold (fun (p v) (def (Tuple url title tags when) p) (add-page v url title tags when))
|
||||
v0
|
||||
[(Tuple "https://doc.rust-lang.org/book/" "The Rust Programming Language" ["rust" "docs"] "2011-03-04")
|
||||
(Tuple "https://www.github.com/rust-lang/rust" "rust-lang/rust" ["code"] "2012-06-30")
|
||||
(Tuple "https://gist.github.com/x/1" "A gist about async" ["rust" "async"] "2012-07-01")
|
||||
(Tuple "https://example.se/kottbullar" "Köttbullar med gräddsås" ["mat"] "2013-01-15")
|
||||
(Tuple "https://example.fr/cafe" "Le café" ["café" "c#"] "2014-02-28")
|
||||
(Tuple "https://notgithub.io/" "" [] "2015-05-05")]))
|
||||
(Tuple root v))
|
||||
|
||||
(: (-> Vault string (Vec string)))
|
||||
(defun (found v text) (vec-map (fun (b) (.url b)) (search-bookmarks v text)))
|
||||
|
||||
(def book "https://doc.rust-lang.org/book/")
|
||||
(def repo "https://www.github.com/rust-lang/rust")
|
||||
(def gist "https://gist.github.com/x/1")
|
||||
(def kott "https://example.se/kottbullar")
|
||||
(def cafe "https://example.fr/cafe")
|
||||
(def notgh "https://notgithub.io/")
|
||||
|
||||
(deftest "parsing"
|
||||
(check (query-empty? (parse-query " t: tag: d: a: a:: - ")))
|
||||
(def q (parse-query "Rust -t:Docs \"two words\" a:2011:2012-06 a:2012-13"))
|
||||
(check (= (.words q) ["rust"]))
|
||||
(check (= (vec-length (.must q)) 3))
|
||||
(check (= (vec-length (.must-not q)) 1))
|
||||
(check (= (query-problem q) "Not a date: 2012-13"))
|
||||
(check (= (query-problem (parse-query "a:2012-02-30")) "Not a date: 2012-02-30"))
|
||||
(check (= (query-problem (parse-query "a:2012:2013-1")) "Not a date: 2012:2013-1"))
|
||||
(check (= (query-problem (parse-query "a:2012-02-29 a::2013 a:2011:")) ""))
|
||||
(check (= (fold-text "Café ÉTÉ") "cafe ete"))
|
||||
(check (= (fold-text "Åsa Ärlig Öl Æble Ø") "åsa ärlig öl æble ø")))
|
||||
|
||||
(deftest "typos"
|
||||
(check (= (typos "rust" "rust" 1) 0))
|
||||
(check (= (typos "rsut" "rust" 1) 1))
|
||||
(check (= (typos "rst" "rust" 1) 1))
|
||||
(check (= (typos "programing" "programming" 2) 1))
|
||||
(check (= (typos "abcdef" "uvwxyz" 2) 3)))
|
||||
|
||||
(deftest "words"
|
||||
(def (Tuple root v) (example))
|
||||
(check (= (vec-length (found v "")) 6))
|
||||
;; The whole word in a title first, then the newest.
|
||||
(check (= (found v "rust") [repo book gist]))
|
||||
(check (= (found v "RUST lang") [repo book]))
|
||||
(check (= (found v "prog") [book]))
|
||||
(check (= (found v "gramming") [book]))
|
||||
(check (= (found v "programing") [book]))
|
||||
(check (= (found v "rsut") [repo book gist]))
|
||||
(check (= (found v "rsu") []))
|
||||
(check (= (found v "async") [gist]))
|
||||
(check (= (found v "cafe") [cafe]))
|
||||
(check (= (found v "CAFÉ") [cafe]))
|
||||
;; ö is not o, but one typo away in a long enough word.
|
||||
(check (= (found v "köttbullar") [kott]))
|
||||
(check (= (found v "gräddsås") [kott]))
|
||||
;; Two typos in a word of eight letters, but not in a quoted text.
|
||||
(check (= (found v "graddsas") [kott]))
|
||||
(check (= (found v "\"graddsas\"") []))
|
||||
(check (= (found v "\"kottbullar\"") [kott]))
|
||||
(check (= (found v "\"köttbullar med\"") [kott]))
|
||||
(check (= (found v "\"med köttbullar\"") []))
|
||||
(directory-delete-tree root))
|
||||
|
||||
(deftest "tags, domains and days"
|
||||
(def (Tuple root v) (example))
|
||||
(check (= (found v "t:rust") [gist book]))
|
||||
(check (= (found v "tag:RUST") [gist book]))
|
||||
(check (= (found v "t:rus") []))
|
||||
(check (= (found v "t:cafe") [cafe]))
|
||||
(check (= (found v "t:\"c#\"") [cafe]))
|
||||
(check (= (found v "t:rust -t:docs") [gist]))
|
||||
(check (= (found v "d:github") [notgh gist repo]))
|
||||
(check (= (found v "d:github.com") [gist repo]))
|
||||
(check (= (found v "d:www.github.com") [gist repo]))
|
||||
(check (= (found v "d:gist.github.com") [gist]))
|
||||
(check (= (found v "-d:github") [cafe kott book]))
|
||||
(check (= (found v "a:2012") [gist repo]))
|
||||
(check (= (found v "a:2012-06") [repo]))
|
||||
(check (= (found v "a:2012-06-30") [repo]))
|
||||
(check (= (found v "a:2011:2012-06") [repo book]))
|
||||
(check (= (found v "a:2013:") [notgh cafe kott]))
|
||||
(check (= (found v "a::2011-03-04") [book]))
|
||||
(check (= (found v "a:2014-02") [cafe]))
|
||||
(check (= (found v "-a:2011:2014") [notgh]))
|
||||
(check (= (found v "a:2012-13") []))
|
||||
(check (= (found v "rust a:2012 d:github.com") [repo gist]))
|
||||
(check (= (found v "-rust") [notgh cafe kott]))
|
||||
(directory-delete-tree root))
|
||||
|
||||
(run-tests)
|
||||
660
tests/store.bjo
Normal file
660
tests/store.bjo
Normal file
|
|
@ -0,0 +1,660 @@
|
|||
;; This Source Code Form is subject to the terms of the Mozilla Public
|
||||
;; License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
;; file, You can obtain one at http://mozilla.org/MPL/2.0/.
|
||||
|
||||
;; bjomarks/tests/store.bjo — (bjomarks store): vaults in folders of the
|
||||
;; temp directory, with two or three devices that sync through one shared
|
||||
;; folder, and files that were changed, replaced or renamed.
|
||||
;;
|
||||
;; bjo run tests/store.bjo
|
||||
;;
|
||||
;; The tests use a cost of 1 iteration over 8 KiB, so that they are quick.
|
||||
;; `at` sets the clock, so that the order of changes is known.
|
||||
|
||||
(import (std prelude))
|
||||
(import (std test))
|
||||
(import (std os))
|
||||
(import (std datetime))
|
||||
(import (std uuid))
|
||||
(import (text json))
|
||||
(import (bjosodium core))
|
||||
(import (bjomarks binary))
|
||||
(import (bjomarks bookmark))
|
||||
(import (bjomarks keys))
|
||||
(import (bjomarks store))
|
||||
|
||||
(def cheap (KeyCost (iterations 1) (memory-kib 8)))
|
||||
|
||||
(: (-> string Instant))
|
||||
(defun (instant text)
|
||||
(match (iso8601->instant text)
|
||||
((Some i) i)
|
||||
(None (panic! (str "not an instant: " text)))))
|
||||
|
||||
;; Calls `f` with the clock at `text`.
|
||||
(: (-> string (-> %a) %a))
|
||||
(defun (at text f)
|
||||
(parameterize ((current-clock (fixed-clock (instant text) utc))) (f)))
|
||||
|
||||
;; Three folders: the shared one and one for each of two devices.
|
||||
(type (: Folders (Record (: shared string) (: one string) (: two string) (: root string))))
|
||||
|
||||
(: (-> Folders))
|
||||
(defun (folders)
|
||||
(def root (make-temp-directory #:prefix "bjomarks-test-"))
|
||||
(Folders (shared (path-combine root "shared")) (one (path-combine root "one"))
|
||||
(two (path-combine root "two")) (root root)))
|
||||
|
||||
(: (-> StoreError string))
|
||||
(defun (store-error e)
|
||||
(match e
|
||||
(WrongPassword "WrongPassword")
|
||||
((NoVault why) (str "NoVault: " why))
|
||||
((VaultExists why) (str "VaultExists: " why))
|
||||
((OtherVault why) (str "OtherVault: " why))
|
||||
((BadFile why) (str "BadFile: " why))))
|
||||
|
||||
(: (-> (Result StoreError Vault) Vault))
|
||||
(defun (must r)
|
||||
(match r
|
||||
((Ok v) v)
|
||||
((Err e) (panic! (store-error e)))))
|
||||
|
||||
(: (-> (Result StoreError (Tuple Vault SyncReport)) Vault))
|
||||
(defun (must-join r)
|
||||
(match r
|
||||
((Ok (Tuple v _)) v)
|
||||
((Err e) (panic! (store-error e)))))
|
||||
|
||||
(: (-> Folders string Vault))
|
||||
(defun (create f local) (must (create-vault (folder-storage (.shared f)) local "hunter2" #:cost cheap)))
|
||||
|
||||
(: (-> Folders string Vault))
|
||||
(defun (join f local) (must-join (join-vault (folder-storage (.shared f)) local "hunter2")))
|
||||
|
||||
(: (-> Folders string string (Result StoreError Vault)))
|
||||
(defun (reopen f local password) (open-vault (folder-storage (.shared f)) local password))
|
||||
|
||||
;; A new bookmark, at the clock's time.
|
||||
(: (-> Vault string (Vec string) (Tuple Vault Bookmark)))
|
||||
(defun (add-bookmark v url tags)
|
||||
(match (vault-add v url #:tags tags)
|
||||
((Ok r) r)
|
||||
((Err why) (panic! why))))
|
||||
|
||||
(: (-> Vault (Tuple Vault SyncReport)))
|
||||
(defun (sync v) (vault-sync v))
|
||||
|
||||
(: (-> Vault Vault))
|
||||
(defun (synced v) (fst (vault-sync v)))
|
||||
|
||||
(: (-> Vault (Vec string)))
|
||||
(defun (urls v) (vec-map #(.url &) (vault-bookmarks v)))
|
||||
|
||||
(: (-> Vault Uuid (Vec string)))
|
||||
(defun (tags-of v id)
|
||||
(match (vault-find v id)
|
||||
((Some b) (.tags b))
|
||||
(None ["<deleted>"])))
|
||||
|
||||
(: (-> Folders Vault string))
|
||||
(defun (file-of f v) (path-combine (.shared f) "devices" (device-file-name (vault-device v))))
|
||||
|
||||
;; ---- One device -----------------------------------------------------------------
|
||||
|
||||
(deftest "a new vault keeps its bookmarks"
|
||||
(def f (folders))
|
||||
(def v0 (create f (.one f)))
|
||||
(check (file-exists? (path-combine (.shared f) "keys.bin")))
|
||||
(check (file-exists? (file-of f v0)))
|
||||
(check (= (vault-revision v0) 1L))
|
||||
(def (Tuple v1 b1) (at "2026-11-11T09:00:00Z" #(add-bookmark v0 "https://example.org/a" ["x"])))
|
||||
(def (Tuple v2 _b2) (at "2026-11-11T10:00:00Z" #(add-bookmark v1 "https://example.org/b" [])))
|
||||
(check (vault-dirty? v2))
|
||||
(def v3 (vault-save v2))
|
||||
(check (not (vault-dirty? v3)))
|
||||
(check (= (vault-revision v3) 2L))
|
||||
(check (= (vault-revision (vault-save v3)) 2L))
|
||||
(vault-close v3)
|
||||
(def again (must (reopen f (.one f) "hunter2")))
|
||||
(check (= (urls again) ["https://example.org/b" "https://example.org/a"]))
|
||||
(check (= (tags-of again (.id b1)) ["x"]))
|
||||
(check (= (vault-id again) (vault-id v0)))
|
||||
(check (= (vault-device again) (vault-device v0)))
|
||||
(check (= (vault-revision again) 2L))
|
||||
(check (not (vault-dirty? again)))
|
||||
(directory-delete-tree (.root f)))
|
||||
|
||||
(deftest "a wrong password, and a device with no vault"
|
||||
(def f (folders))
|
||||
(ignore (create f (.one f)))
|
||||
(check (= (match (reopen f (.one f) "hunter3") ((Ok _) "Ok") ((Err e) (store-error e))) "WrongPassword"))
|
||||
(check-match (reopen f (.two f) "hunter2") (Err (NoVault _)))
|
||||
(check-match (join-vault (folder-storage (.two f)) (.two f) "hunter2") (Err (NoVault _)))
|
||||
(check (= (match (join-vault (folder-storage (.shared f)) (path-combine (.root f) "three") "nope")
|
||||
((Ok _) "Ok") ((Err e) (store-error e)))
|
||||
"WrongPassword"))
|
||||
(directory-delete-tree (.root f)))
|
||||
|
||||
(deftest "a vault is not made twice"
|
||||
(def f (folders))
|
||||
(ignore (create f (.one f)))
|
||||
(check-match (create-vault (folder-storage (.shared f)) (.two f) "pw" #:cost cheap) (Err (VaultExists _)))
|
||||
(check-match (create-vault (folder-storage (path-combine (.root f) "elsewhere")) (.one f) "pw" #:cost cheap)
|
||||
(Err (VaultExists _)))
|
||||
(check-match (join-vault (folder-storage (.shared f)) (.one f) "hunter2") (Err (VaultExists _)))
|
||||
(directory-delete-tree (.root f)))
|
||||
|
||||
(deftest "changes are deleted and put"
|
||||
(def f (folders))
|
||||
(def v0 (create f (.one f)))
|
||||
(def (Tuple v1 b) (add-bookmark v0 "https://example.org/a" ["x"]))
|
||||
(def v2 (vault-put v1 (bookmark-with-tags b ["y" " z" "y"])))
|
||||
(check (= (tags-of v2 (.id b)) ["y" "z"]))
|
||||
(def v3 (vault-delete v2 (.id b)))
|
||||
(check (= (urls v3) []))
|
||||
(check (= (vault-find v3 (.id b)) None))
|
||||
;; The tombstone stays, so that the delete reaches the other devices.
|
||||
(check (= (map-length (vault-entries v3)) 1))
|
||||
(check (= (vault-delete v3 (.id b)) v3))
|
||||
(directory-delete-tree (.root f)))
|
||||
|
||||
(deftest "a delete is undone, and the other devices see it"
|
||||
(def f (folders))
|
||||
(def a0 (create f (.one f)))
|
||||
(def (Tuple a1 b) (at "2026-11-11T09:00:00Z" #(add-bookmark a0 "https://example.org/" ["x"])))
|
||||
(def before (match (map-try-ref (vault-entries a1) (uuid->string (.id b)))
|
||||
((Some e) e)
|
||||
(None (panic! "no entry"))))
|
||||
(def a2 (synced (at "2026-11-11T09:01:00Z" #(vault-delete a1 (.id b)))))
|
||||
(def b0 (join f (.two f)))
|
||||
(check (= (urls b0) []))
|
||||
(def a3 (synced (at "2026-11-11T09:02:00Z" #(vault-restore a2 before))))
|
||||
(check (= (urls a3) ["https://example.org/"]))
|
||||
(check (= (tags-of a3 (.id b)) ["x"]))
|
||||
;; Bound first: `(.stamp (match ...))` makes C# that does not compile.
|
||||
(def restored (match (map-try-ref (vault-entries a3) (uuid->string (.id b))) ((Some e) e) (None before)))
|
||||
(check (> (stamp-compare (.stamp restored) (.stamp before)) 0))
|
||||
(def b1 (synced b0))
|
||||
(check (= (urls b1) ["https://example.org/"]))
|
||||
(check (= (vault-restore a3 (deleted-entry (.stamp before) (.id b))) a3))
|
||||
(directory-delete-tree (.root f)))
|
||||
|
||||
(deftest "the files are padded"
|
||||
(def f (folders))
|
||||
(def v0 (create f (.one f)))
|
||||
(def size (array-length (file-read-bytes (file-of f v0))))
|
||||
;; The header, the nonce and the tag are 51 + 2 * 32 bytes for AEGIS-256,
|
||||
;; and 51 + 24 + 16 for XChaCha20-Poly1305.
|
||||
(def overhead (+ 51 (cipher-nonce-length (preferred-cipher)) (cipher-tag-length (preferred-cipher))))
|
||||
(check (= (- size overhead) 16384))
|
||||
(def more (vec-fold (fun (i v) (fst (add-bookmark v (str "https://example.org/" (int->string i)) ["tag"])))
|
||||
v0 (->vec (range 0 20))))
|
||||
(def saved (vault-save more))
|
||||
(check (= (- (array-length (file-read-bytes (file-of f saved))) overhead) 16384))
|
||||
(directory-delete-tree (.root f)))
|
||||
|
||||
;; ---- Two devices -------------------------------------------------------------------
|
||||
|
||||
(deftest "two devices see each other's changes"
|
||||
(def f (folders))
|
||||
(def a0 (create f (.one f)))
|
||||
(def (Tuple a1 b1) (at "2026-11-11T09:00:00Z" #(add-bookmark a0 "https://example.org/one" ["x"])))
|
||||
(def a2 (vault-save a1))
|
||||
(def b0 (join f (.two f)))
|
||||
(check (= (urls b0) ["https://example.org/one"]))
|
||||
(check (not (= (vault-device b0) (vault-device a2))))
|
||||
(def (Tuple b1x b2) (at "2026-11-11T10:00:00Z" #(add-bookmark b0 "https://example.org/two" [])))
|
||||
(def b2x (at "2026-11-11T10:01:00Z" #(vault-delete b1x (.id b1))))
|
||||
(def (Tuple b3 report-b) (sync b2x))
|
||||
(check (.wrote report-b))
|
||||
(def (Tuple a3 report-a) (sync a2))
|
||||
(check (= (.files-merged report-a) 2))
|
||||
(check (= (.entries-changed report-a) 2))
|
||||
(check (= (.problems report-a) []))
|
||||
(check (= (urls a3) ["https://example.org/two"]))
|
||||
(def a4 (at "2026-11-11T11:00:00Z" #(vault-put a3 (bookmark-with-tags b2 ["new"]))))
|
||||
(def a5 (synced a4))
|
||||
(def b4 (synced b3))
|
||||
(check (= (tags-of b4 (.id b2)) ["new"]))
|
||||
;; Nothing new: nothing is written.
|
||||
(def (Tuple _b5 again) (sync b4))
|
||||
(check (= (.entries-changed again) 0))
|
||||
(check (not (.wrote again)))
|
||||
(check (= (vault-revision a5) (vault-revision (synced a5))))
|
||||
(directory-delete-tree (.root f)))
|
||||
|
||||
(deftest "a title reaches the other devices, and a later title wins"
|
||||
(def f (folders))
|
||||
(def a0 (create f (.one f)))
|
||||
(def (Ok (Tuple a1 b)) (vault-add a0 "https://example.org/" #:title (Some " Example\nDomain "))
|
||||
:leave-with (check-fail "vault-add refused a good address"))
|
||||
(check (= (.title b) (Some "Example Domain")))
|
||||
(def a2 (vault-save a1))
|
||||
(def b0 (join f (.two f)))
|
||||
(check (= (vec-map #(.title &) (vault-bookmarks b0)) [(Some "Example Domain")]))
|
||||
(def b1 (synced (vault-put b0 (bookmark-with-title b (Some "Fetched")))))
|
||||
(def a3 (synced a2))
|
||||
(check (= (vec-map #(.title &) (vault-bookmarks a3)) [(Some "Fetched")]))
|
||||
(check (= (vec-map #(.title &) (vault-bookmarks b1)) [(Some "Fetched")]))
|
||||
(directory-delete-tree (.root f)))
|
||||
|
||||
(deftest "the later change wins, whichever device syncs first"
|
||||
(def f (folders))
|
||||
(def a0 (create f (.one f)))
|
||||
(def (Tuple a1 b) (at "2026-11-11T09:00:00Z" #(add-bookmark a0 "https://example.org/" [])))
|
||||
(def a2 (synced a1))
|
||||
(def b0 (join f (.two f)))
|
||||
;; Both change the bookmark before either syncs. The phone's change is later.
|
||||
(def a3 (at "2026-11-11T12:00:00Z" #(vault-put a2 (bookmark-with-tags b ["laptop"]))))
|
||||
(def b1 (at "2026-11-11T12:00:05Z" #(vault-put b0 (bookmark-with-tags b ["phone"]))))
|
||||
(def a4 (synced a3))
|
||||
(def b2 (synced b1))
|
||||
(def a5 (synced a4))
|
||||
(check (= (tags-of a5 (.id b)) ["phone"]))
|
||||
(check (= (tags-of b2 (.id b)) ["phone"]))
|
||||
(directory-delete-tree (.root f)))
|
||||
|
||||
(deftest "a delete wins over an older change, and a later change brings it back"
|
||||
(def f (folders))
|
||||
(def a0 (create f (.one f)))
|
||||
(def (Tuple a1 b) (at "2026-11-11T09:00:00Z" #(add-bookmark a0 "https://example.org/" [])))
|
||||
(def a2 (synced a1))
|
||||
(def b0 (join f (.two f)))
|
||||
(def a3 (at "2026-11-11T12:00:00Z" #(vault-put a2 (bookmark-with-tags b ["edited"]))))
|
||||
(def b1 (at "2026-11-11T12:00:05Z" #(vault-delete b0 (.id b))))
|
||||
(def a4 (synced (synced a3)))
|
||||
(def b2 (synced b1))
|
||||
(def a5 (synced a4))
|
||||
(check (= (urls a5) []))
|
||||
(check (= (urls b2) []))
|
||||
(def a6 (at "2026-11-11T13:00:00Z" #(vault-put a5 (bookmark-with-tags b ["back"]))))
|
||||
(def a7 (synced a6))
|
||||
(def b3 (synced b2))
|
||||
(check (= (tags-of b3 (.id b)) ["back"]))
|
||||
(check (= (tags-of a7 (.id b)) ["back"]))
|
||||
(directory-delete-tree (.root f)))
|
||||
|
||||
(deftest "the clock does not go back when the wall clock does"
|
||||
(def f (folders))
|
||||
(def a0 (create f (.one f)))
|
||||
(def (Tuple a1 b) (at "2026-11-11T12:00:00Z" #(add-bookmark a0 "https://example.org/" [])))
|
||||
(def a2 (synced a1))
|
||||
(def b0 (join f (.two f)))
|
||||
;; This device's clock is an hour behind. Its change is still the later one.
|
||||
(def b1 (at "2026-11-11T11:00:00Z" #(vault-put b0 (bookmark-with-tags b ["after"]))))
|
||||
(def b2 (synced b1))
|
||||
(def a3 (synced a2))
|
||||
(check (= (tags-of a3 (.id b)) ["after"]))
|
||||
(check (= (tags-of b2 (.id b)) ["after"]))
|
||||
(directory-delete-tree (.root f)))
|
||||
|
||||
(deftest "a sync in the background, and the changes made while it ran"
|
||||
(def f (folders))
|
||||
(def a0 (create f (.one f)))
|
||||
(def b0 (join f (.two f)))
|
||||
(def (Tuple b1 _) (at "2026-11-11T08:00:00Z" #(add-bookmark b0 "https://example.org/from-b" [])))
|
||||
(def _b2 (synced b1))
|
||||
(def (Tuple a1 first) (at "2026-11-11T09:00:00Z" #(add-bookmark a0 "https://example.org/first" [])))
|
||||
;; The sync runs on a1; meanwhile the vault becomes a2.
|
||||
(def (Tuple done _) (sync a1))
|
||||
(def (Tuple a2 _) (at "2026-11-11T09:00:01Z" #(add-bookmark a1 "https://example.org/meanwhile" [])))
|
||||
(def a3 (at "2026-11-11T09:00:02Z" #(vault-put a2 (bookmark-with-tags first ["edited"]))))
|
||||
(def merged (vault-merge a3 done))
|
||||
(check (= (urls merged) ["https://example.org/meanwhile" "https://example.org/first"
|
||||
"https://example.org/from-b"]))
|
||||
(check (= (tags-of merged (.id first)) ["edited"]))
|
||||
(check (vault-dirty? merged))
|
||||
(check (= (vault-revision merged) (vault-revision done)))
|
||||
;; The next sync writes the changes made while the first ran.
|
||||
(def (Tuple again report) (sync merged))
|
||||
(check (.wrote report))
|
||||
(check (= (vault-revision again) (+ (vault-revision done) 1L)))
|
||||
(check (not (vault-dirty? (vault-merge again again))))
|
||||
;; Nothing changed while a sync ran: nothing more to write.
|
||||
(def (Tuple done2 _) (sync again))
|
||||
(check (not (vault-dirty? (vault-merge again done2))))
|
||||
(def c0 (join f (path-combine (.root f) "three")))
|
||||
(check (= (tags-of c0 (.id first)) ["edited"]))
|
||||
(directory-delete-tree (.root f)))
|
||||
|
||||
;; ---- Files that are not right ------------------------------------------------------
|
||||
|
||||
(: (-> SyncReport string))
|
||||
(defun (problems-of r) (string-join (.problems r) " | "))
|
||||
|
||||
(deftest "a changed file is skipped and reported"
|
||||
(def f (folders))
|
||||
(def a0 (create f (.one f)))
|
||||
(def b0 (join f (.two f)))
|
||||
(def (Tuple b1 _) (add-bookmark b0 "https://example.org/secret" []))
|
||||
(def b2 (synced b1))
|
||||
(def path (file-of f b2))
|
||||
(def bytes (file-read-bytes path))
|
||||
(put-u8! bytes 200 (bitwise-xor (get-u8 bytes 200) 1))
|
||||
(file-write-bytes path bytes)
|
||||
(def (Tuple a1 report) (sync a0))
|
||||
(check (= (urls a1) []))
|
||||
(check (= (.files-merged report) 1))
|
||||
(check (string-contains? (problems-of report) "it does not decrypt"))
|
||||
(check (string-contains? (problems-of report) (device-file-name (vault-device b2))))
|
||||
(directory-delete-tree (.root f)))
|
||||
|
||||
(deftest "an older copy of a file is reported, and does not undo anything"
|
||||
(def f (folders))
|
||||
(def a0 (create f (.one f)))
|
||||
(def b0 (join f (.two f)))
|
||||
(def path (file-of f b0))
|
||||
(def old (file-read-bytes path))
|
||||
(def (Tuple b1 _) (at "2026-11-11T09:00:00Z" #(add-bookmark b0 "https://example.org/kept" [])))
|
||||
(def _b2 (synced b1))
|
||||
(def a1 (synced a0))
|
||||
(check (= (urls a1) ["https://example.org/kept"]))
|
||||
(file-write-bytes path old)
|
||||
(def (Tuple a2 report) (sync a1))
|
||||
(check (string-contains? (problems-of report) "revision 1 is older than revision 2"))
|
||||
(check (= (urls a2) ["https://example.org/kept"]))
|
||||
(directory-delete-tree (.root f)))
|
||||
|
||||
(deftest "a file of another vault, and a file under another name"
|
||||
(def f (folders))
|
||||
(def a0 (create f (.one f)))
|
||||
(def b0 (join f (.two f)))
|
||||
(def elsewhere (path-combine (.root f) "elsewhere"))
|
||||
(def other (must (create-vault (folder-storage elsewhere) (path-combine (.root f) "three") "pw" #:cost cheap)))
|
||||
(def devices (path-combine (.shared f) "devices"))
|
||||
(file-copy (path-combine elsewhere "devices" (device-file-name (vault-device other)))
|
||||
(path-combine devices (device-file-name (vault-device other))))
|
||||
(file-copy (file-of f b0) (path-combine devices (device-file-name (uuid-v4))))
|
||||
(file-copy (file-of f b0) (path-combine devices "laptop (conflicted copy).bin"))
|
||||
(file-write-text (path-combine devices "notes.txt") "not a device file")
|
||||
(def (Tuple _a1 report) (sync a0))
|
||||
(def text (problems-of report))
|
||||
(check (= (vec-length (.problems report)) 3))
|
||||
(check (string-contains? text "it belongs to another vault"))
|
||||
(check (string-contains? text (str "it holds the file of the device " (uuid->string (vault-device b0)))))
|
||||
(check (string-contains? text "laptop (conflicted copy).bin: the name is not <device uuid>.bin"))
|
||||
(check (= (.files-merged report) 2))
|
||||
(directory-delete-tree (.root f)))
|
||||
|
||||
(deftest "a file from a newer version is reported"
|
||||
(def f (folders))
|
||||
(def a0 (create f (.one f)))
|
||||
(def b0 (join f (.two f)))
|
||||
(def path (file-of f b0))
|
||||
(def bytes (file-read-bytes path))
|
||||
(put-u16! bytes 4 2)
|
||||
(file-write-bytes path bytes)
|
||||
(def (Tuple _a1 report) (sync a0))
|
||||
(check (string-contains? (problems-of report) "device file version 2 is newer than this version reads (1)"))
|
||||
(directory-delete-tree (.root f)))
|
||||
|
||||
;; ---- Losing files ------------------------------------------------------------------
|
||||
|
||||
(deftest "a device's file that the storage lost is written again"
|
||||
(def f (folders))
|
||||
(def a0 (create f (.one f)))
|
||||
(def (Tuple a1 _) (add-bookmark a0 "https://example.org/" []))
|
||||
(def a2 (synced a1))
|
||||
(file-delete (file-of f a2))
|
||||
(def (Tuple a3 report) (sync a2))
|
||||
(check (.wrote report))
|
||||
(check (file-exists? (file-of f a3)))
|
||||
(def b0 (join f (.two f)))
|
||||
(check (= (urls b0) ["https://example.org/"]))
|
||||
(directory-delete-tree (.root f)))
|
||||
|
||||
(deftest "a vault opens from the storage when state.bin is gone, and from the local keys when keys.bin is"
|
||||
(def f (folders))
|
||||
(def a0 (create f (.one f)))
|
||||
(def (Tuple a1 _) (add-bookmark a0 "https://example.org/" []))
|
||||
(def a2 (synced a1))
|
||||
(file-delete (path-combine (.one f) "state.bin"))
|
||||
(def a3 (must (reopen f (.one f) "hunter2")))
|
||||
(check (= (urls a3) ["https://example.org/"]))
|
||||
(check (= (vault-revision a3) (vault-revision a2)))
|
||||
(file-delete (path-combine (.shared f) "keys.bin"))
|
||||
(def a4 (must (reopen f (.one f) "hunter2")))
|
||||
(def (Tuple _a5 report) (sync a4))
|
||||
(check (string-contains? (problems-of report) "keys.bin was missing"))
|
||||
(check (file-exists? (path-combine (.shared f) "keys.bin")))
|
||||
(directory-delete-tree (.root f)))
|
||||
|
||||
(deftest "a storage of another vault does not open"
|
||||
(def f (folders))
|
||||
(ignore (create f (.one f)))
|
||||
(def elsewhere (path-combine (.root f) "elsewhere"))
|
||||
(ignore (create-vault (folder-storage elsewhere) (path-combine (.root f) "three") "hunter2" #:cost cheap))
|
||||
(check-match (open-vault (folder-storage elsewhere) (.one f) "hunter2") (Err (OtherVault _)))
|
||||
(directory-delete-tree (.root f)))
|
||||
|
||||
;; ---- Passwords --------------------------------------------------------------------
|
||||
|
||||
(: (-> Folders (Array byte)))
|
||||
(defun (shared-keys f) (file-read-bytes (path-combine (.shared f) "keys.bin")))
|
||||
|
||||
(: (-> Folders (Array byte) void))
|
||||
(defun (set-shared-keys! f keys) (file-write-bytes (path-combine (.shared f) "keys.bin") keys))
|
||||
|
||||
(: (-> Folders string (Array byte)))
|
||||
(defun (own-keys f local) (file-read-bytes (path-combine local "keys.bin")))
|
||||
|
||||
(: (-> (Result string Vault) Vault))
|
||||
(defun (changed r)
|
||||
(match r
|
||||
((Ok v) v)
|
||||
((Err why) (panic! why))))
|
||||
|
||||
(: (-> SyncReport string bool))
|
||||
(defun (told? report text)
|
||||
(not (vec-empty? (vec-filter (fun (p) (string-contains? p text)) (.problems report)))))
|
||||
|
||||
(: (-> (Result StoreError Vault) Vault))
|
||||
(defun (opened r) (must r))
|
||||
|
||||
(deftest "a new password comes with a new key, and the other devices read on"
|
||||
(def f (folders))
|
||||
(def a0 (fst (add-bookmark (create f (.one f)) "https://example.org/before" [])))
|
||||
(def b0 (join f (.two f)))
|
||||
(def old-keys (shared-keys f))
|
||||
(def a1 (changed (vault-change-password (vault-save a0) "correct horse" #:cost cheap)))
|
||||
(check-match (reopen f (.one f) "hunter2") (Err WrongPassword))
|
||||
(check-match (reopen f (.one f) "correct horse") (Ok _))
|
||||
(def a2 (vault-save (fst (add-bookmark a1 "https://example.org/after" []))))
|
||||
;; An old copy of keys.bin and the old password do not open what was
|
||||
;; written after the change.
|
||||
(def (Ok old) (unlock-keys old-keys "hunter2") :leave-with (check-fail "the old keys did not open"))
|
||||
(check-match (decode-device-file (file-read-bytes (file-of f a2)) (.vault-id old)
|
||||
[(Tuple (.key-id old) (.dek old))])
|
||||
(Err _))
|
||||
;; The other device, open, reads on with the key it has, and is told.
|
||||
(def (Tuple b1 report) (sync b0))
|
||||
(check (told? report "The password was changed on another device"))
|
||||
(def b2 (synced (fst (add-bookmark b1 "https://example.org/from-b" []))))
|
||||
;; Its file is written with the earlier key, which the first device reads.
|
||||
(def a3 (synced a2))
|
||||
(check (vec-contains? (urls a3) "https://example.org/from-b"))
|
||||
(check (not (= (vault-change-password b2 "another" #:cost cheap) (Ok b2))))
|
||||
(check-match (vault-change-password b2 "another" #:cost cheap) (Err _))
|
||||
;; The old password no longer opens it.
|
||||
(check-match (reopen f (.two f) "hunter2") (Err WrongPassword))
|
||||
(def (Tuple b3 report3) (sync (opened (reopen f (.two f) "correct horse"))))
|
||||
(check (= (.problems report3) []))
|
||||
(check (vec-contains? (urls b3) "https://example.org/after"))
|
||||
;; Its copy of keys.bin is the new one, so it opens without the storage too.
|
||||
(check (bytes=? (own-keys f (.two f)) (shared-keys f)))
|
||||
(file-delete (path-combine (.shared f) "keys.bin"))
|
||||
(check-match (reopen f (.two f) "correct horse") (Ok _))
|
||||
(check-match (reopen f (.two f) "hunter2") (Err WrongPassword))
|
||||
(directory-delete-tree (.root f)))
|
||||
|
||||
(deftest "two devices change the password at once, to two passwords"
|
||||
(def f (folders))
|
||||
(def a0 (create f (.one f)))
|
||||
(def b0 (synced (fst (add-bookmark (join f (.two f)) "https://example.org/b-before" []))))
|
||||
(def original (shared-keys f))
|
||||
(def a1 (changed (vault-change-password (synced a0) "pw-a" #:cost cheap)))
|
||||
(def keys-a (shared-keys f))
|
||||
;; The other device changes it too, before it sees the first change.
|
||||
(set-shared-keys! f original)
|
||||
(def b1 (changed (vault-change-password b0 "pw-b" #:cost cheap)))
|
||||
(def b2 (vault-save (fst (add-bookmark b1 "https://example.org/b-after" []))))
|
||||
;; The sync keeps the first device's keys.bin.
|
||||
(set-shared-keys! f keys-a)
|
||||
(def (Tuple b3 report) (sync b2))
|
||||
(check (told? report "at the same time"))
|
||||
;; It writes with the key that both have, so the first device reads it.
|
||||
(def a2 (synced a1))
|
||||
(check (vec-contains? (urls a2) "https://example.org/b-after"))
|
||||
(vault-close b3)
|
||||
;; Its own password still opens it, from its copy of keys.bin.
|
||||
(def (Tuple b4 report4) (sync (opened (reopen f (.two f) "pw-b"))))
|
||||
(check (told? report4 "at the same time"))
|
||||
(vault-close b4)
|
||||
;; The other device's password opens all of it.
|
||||
(def (Tuple b5 report5) (sync (opened (reopen f (.two f) "pw-a"))))
|
||||
(check (= (.problems report5) []))
|
||||
(check (vec-contains? (urls b5) "https://example.org/b-after"))
|
||||
(check (vec-contains? (urls b5) "https://example.org/b-before"))
|
||||
(check (bytes=? (own-keys f (.two f)) keys-a))
|
||||
(directory-delete-tree (.root f)))
|
||||
|
||||
(deftest "two devices change the password at once, to the same password"
|
||||
(def f (folders))
|
||||
(def a0 (create f (.one f)))
|
||||
(def b0 (synced (join f (.two f))))
|
||||
(def original (shared-keys f))
|
||||
(def a1 (changed (vault-change-password (synced a0) "same" #:cost cheap)))
|
||||
(def keys-a (shared-keys f))
|
||||
(set-shared-keys! f original)
|
||||
(def b1 (changed (vault-change-password b0 "same" #:cost cheap)))
|
||||
(vault-close (vault-save (fst (add-bookmark b1 "https://example.org/b-after" []))))
|
||||
(set-shared-keys! f keys-a)
|
||||
;; It opens with both keys files: its file is written with its own key.
|
||||
(def (Tuple b2 report) (sync (opened (reopen f (.two f) "same"))))
|
||||
(check (= (.problems report) []))
|
||||
(check (vec-contains? (urls b2) "https://example.org/b-after"))
|
||||
(check (vec-contains? (urls (synced a1)) "https://example.org/b-after"))
|
||||
(check (bytes=? (own-keys f (.two f)) keys-a))
|
||||
(directory-delete-tree (.root f)))
|
||||
|
||||
(deftest "a keys.bin that was replaced does not lock a device out"
|
||||
(def f (folders))
|
||||
(def a0 (vault-save (fst (add-bookmark (create f (.one f)) "https://example.org/a" []))))
|
||||
(def mine (own-keys f (.one f)))
|
||||
;; The same vault id, another key, and another password.
|
||||
(set-shared-keys! f (wrap-keys (vault-id a0) 7 (make-aead-key XChaCha20Poly1305) "not yours" #:cost cheap))
|
||||
(def (Tuple a1 report) (sync (opened (reopen f (.one f) "hunter2"))))
|
||||
(check (told? report "holds none of this device's keys"))
|
||||
(check (= (urls a1) ["https://example.org/a"]))
|
||||
(check (bytes=? (own-keys f (.one f)) mine))
|
||||
(check-match (reopen f (.one f) "not yours") (Err _))
|
||||
(directory-delete-tree (.root f)))
|
||||
|
||||
;; ---- Fields from a newer version --------------------------------------------------
|
||||
|
||||
(deftest "fields that a newer version wrote are kept through a change"
|
||||
(def f (folders))
|
||||
(def a0 (create f (.one f)))
|
||||
(def (Ok unlocked) (unlock-keys (file-read-bytes (path-combine (.shared f) "keys.bin")) "hunter2")
|
||||
:leave-with (check-fail "the keys did not open"))
|
||||
;; A third device, of a newer version, wrote a bookmark with a rating.
|
||||
(def newer (uuid-v4))
|
||||
(def id (uuid-v4))
|
||||
(def b (Bookmark (id id) (url "https://example.org/") (title (Some "Example"))
|
||||
(added (instant "2026-11-11T09:00:00Z")) (tags []) (archive None)))
|
||||
(def e (Entry (stamp (Stamp (ms 1000L) (counter 0) (device newer))) (state (Live b))
|
||||
(extra [(Tuple "rating" (JsonInt 4L))])))
|
||||
(def file (encode-device-file (FileHead (head-vault (.vault-id unlocked)) (head-device newer)
|
||||
(head-revision 1L) (head-key-id (.key-id unlocked))
|
||||
(head-cipher XChaCha20Poly1305))
|
||||
(.dek unlocked)
|
||||
(DeviceDoc (device newer) (seen (map-empty)) (entries [e]))))
|
||||
(file-write-bytes (path-combine (.shared f) "devices" (device-file-name newer)) file)
|
||||
(def a1 (synced a0))
|
||||
(def a2 (synced (vault-put a1 (bookmark-with-tags b ["tagged"]))))
|
||||
(match (map-try-ref (vault-entries a2) (uuid->string id))
|
||||
((Some kept)
|
||||
(check (= (.extra kept) [(Tuple "rating" (JsonInt 4L))]))
|
||||
(check (= (match (.state kept) ((Live k) (.title k)) ((Deleted _) None)) (Some "Example")))
|
||||
(check (> (stamp-compare (.stamp kept) (.stamp e)) 0)))
|
||||
(None (check-fail "the bookmark is gone")))
|
||||
(directory-delete-tree (.root f)))
|
||||
|
||||
;; ---- A storage of functions ---------------------------------------------------------
|
||||
|
||||
;; A `FunctionStorage` that keeps its files in memory, by name, as the
|
||||
;; folder of Android's Storage Access Framework is kept behind Avalonia.
|
||||
(: (-> (Box (Map string (Array byte))) Storage))
|
||||
(defun (memory-storage files)
|
||||
(: (-> string (Option (Array byte))))
|
||||
(defun (read name) (map-try-ref (box-ref files) name))
|
||||
(: (-> string (Array byte) void))
|
||||
(defun (write name bytes) (box-set! files (map-set (box-ref files) name bytes)))
|
||||
(: (-> string (Vec string)))
|
||||
(defun (list-names dir)
|
||||
(def prefix (str dir "/"))
|
||||
(vec-map (fun (k) (string-drop k (string-count prefix)))
|
||||
(vec-filter (fun (k) (string-starts-with? k prefix)) (->vec (map-keys (box-ref files))))))
|
||||
(function-storage "memory" read write list-names))
|
||||
|
||||
(deftest "two devices sync through a storage of functions"
|
||||
(def root (make-temp-directory #:prefix "bjomarks-test-"))
|
||||
(def files (make-box (: (map-empty) (Map string (Array byte)))))
|
||||
(def storage (memory-storage files))
|
||||
(check (= (storage-label storage) "memory"))
|
||||
(def a0 (must (create-vault storage (path-combine root "one") "hunter2" #:cost cheap)))
|
||||
(check (some? (storage-read storage "keys.bin")))
|
||||
(check (= (storage-list storage devices-dir) [(device-file-name (vault-device a0))]))
|
||||
(def a1 (synced (fst (add-bookmark a0 "https://example.org/a" ["x"]))))
|
||||
(def b0 (must-join (join-vault storage (path-combine root "two") "hunter2")))
|
||||
(check (= (urls b0) ["https://example.org/a"]))
|
||||
(def b1 (synced (fst (at "2026-11-11T09:00:00Z" #(add-bookmark b0 "https://example.org/b" [])))))
|
||||
(check (= (vec-length (storage-list storage devices-dir)) 2))
|
||||
(def a2 (synced a1))
|
||||
(check (= (vec-sort (urls a2)) ["https://example.org/a" "https://example.org/b"]))
|
||||
;; A temporary file of a syncer, beginning with ".", is not a device's.
|
||||
(storage-write storage "devices/.syncthing.x.tmp" (make-array 3))
|
||||
(check (= (vec-length (storage-list storage devices-dir)) 2))
|
||||
(def (Tuple _ report) (vault-sync b1))
|
||||
(check (vec-empty? (.problems report)))
|
||||
(directory-delete-tree root))
|
||||
|
||||
(deftest "each shared folder has a device folder of its own"
|
||||
(def f (folders))
|
||||
(def first (folder-storage (.shared f)))
|
||||
(def second-path (path-combine (.root f) "second"))
|
||||
(def second (folder-storage second-path))
|
||||
(def a (device-folder (.one f) (.shared f) first))
|
||||
(def b (device-folder (.one f) second-path second))
|
||||
(check (not (= a b)))
|
||||
(check (= a (device-folder (.one f) (.shared f) first)))
|
||||
(ignore (must (create-vault first a "hunter2" #:cost cheap)))
|
||||
;; The second folder is empty: a new vault, not the first one.
|
||||
(check-match (open-vault second b "hunter2") (Err (NoVault _)))
|
||||
(ignore (must (create-vault second b "other" #:cost cheap)))
|
||||
(check (= (vec-length (vault-bookmarks (must (open-vault first a "hunter2")))) 0))
|
||||
(check-match (open-vault second b "other") (Ok _))
|
||||
(directory-delete-tree (.root f)))
|
||||
|
||||
(deftest "the files of the one device folder before move to its shared folder's"
|
||||
(def f (folders))
|
||||
(def first (folder-storage (.shared f)))
|
||||
(def v (must (create-vault first (.one f) "hunter2" #:cost cheap)))
|
||||
(def other-path (path-combine (.root f) "other"))
|
||||
(def other (folder-storage other-path))
|
||||
(ignore (must (create-vault other (.two f) "pw" #:cost cheap)))
|
||||
;; A folder of another vault leaves them where they are.
|
||||
(def b (device-folder (.one f) other-path other))
|
||||
(check (not (file-exists? (path-combine b "device.json"))))
|
||||
(check (file-exists? (path-combine (.one f) "device.json")))
|
||||
;; The folder of their vault gets them.
|
||||
(def a (device-folder (.one f) (.shared f) first))
|
||||
(check (file-exists? (path-combine a "device.json")))
|
||||
(check (file-exists? (path-combine a "keys.bin")))
|
||||
(check (not (file-exists? (path-combine (.one f) "device.json"))))
|
||||
(def again (must (open-vault first a "hunter2")))
|
||||
(check (= (vault-id again) (vault-id v)))
|
||||
(directory-delete-tree (.root f)))
|
||||
|
||||
(run-tests)
|
||||
272
tests/title.bjo
Normal file
272
tests/title.bjo
Normal file
|
|
@ -0,0 +1,272 @@
|
|||
;; This Source Code Form is subject to the terms of the Mozilla Public
|
||||
;; License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
;; file, You can obtain one at http://mozilla.org/MPL/2.0/.
|
||||
|
||||
;; bjomarks/tests/title.bjo — (bjomarks title): the title in the bytes of a
|
||||
;; page, and the title fetched from a server on the loopback.
|
||||
;;
|
||||
;; bjo run tests/title.bjo
|
||||
;;
|
||||
;; The server is written here, on (std net), so that a test can make it
|
||||
;; slow, make it stop after the title, or send bytes of another charset.
|
||||
|
||||
(import (std prelude))
|
||||
(import (std test))
|
||||
(import (std datetime))
|
||||
(import (std net))
|
||||
(import (std ports))
|
||||
(import (only (text encodings) iso-8859-1))
|
||||
(import (bjomarks title))
|
||||
|
||||
(: (-> string (Array byte)))
|
||||
(defun (bytes-of text) (string->bytes text))
|
||||
|
||||
(: (-> (Array byte) (Option string) (Option string)))
|
||||
(defun (title-in bytes content-type) (page-title bytes (array-length bytes) content-type))
|
||||
|
||||
;; ---- The title in the bytes ----------------------------------------------------------
|
||||
|
||||
(deftest "the title of a page"
|
||||
#:cases ((html wanted)
|
||||
("<html><head><title>Example Domain</title></head></html>" (Some "Example Domain"))
|
||||
("<HTML><HEAD><TITLE>Upper Case</TITLE></HEAD>" (Some "Upper Case"))
|
||||
("<title lang=\"en\">With attributes</title>" (Some "With attributes"))
|
||||
("<head><titlebar>no</titlebar><title>After a longer tag</title>" (Some "After a longer tag"))
|
||||
("<title>\n Rust\n docs\n </title>" (Some "Rust docs"))
|
||||
("<title>Tom & Jerry — "Home" 's x</title>"
|
||||
(Some "Tom & Jerry — \"Home\" 's x"))
|
||||
("<title>First</title><title>Second</title>" (Some "First"))
|
||||
("<html><head></head><body>none</body>" None)
|
||||
("<title></title>" None)
|
||||
("<title> </title>" None)
|
||||
("<title>Cut off" None)
|
||||
("<title" None))
|
||||
(check (= (title-in (bytes-of html) None) wanted)))
|
||||
|
||||
(deftest "only the first n bytes are read"
|
||||
;; 22 bytes; the end tag is whole at 21 without its `>`.
|
||||
(def bytes (bytes-of "<title>Example</title>"))
|
||||
(check (= (page-title bytes 21 None) (Some "Example")))
|
||||
(check (= (page-title bytes 20 None) None))
|
||||
(check (= (page-title bytes 0 None) None)))
|
||||
|
||||
(deftest "the charset is the header's, else the page's, else UTF-8"
|
||||
(def latin (string->bytes "<title>Café crème</title>" #:encoding iso-8859-1))
|
||||
(check (= (title-in latin (Some "text/html; charset=ISO-8859-1")) (Some "Café crème")))
|
||||
(check (= (title-in latin (Some "text/html; charset=\"windows-1252\"")) (Some "Café crème")))
|
||||
(def meta (string->bytes "<meta charset=\"iso-8859-1\"><title>Café</title>" #:encoding iso-8859-1))
|
||||
(check (= (title-in meta (Some "text/html")) (Some "Café")))
|
||||
(def equiv (string->bytes (str "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=windows-1252\">"
|
||||
"<title>Café</title>")
|
||||
#:encoding iso-8859-1))
|
||||
(check (= (title-in equiv None) (Some "Café")))
|
||||
;; The header wins over the page.
|
||||
(check (= (title-in (bytes-of "<meta charset=\"iso-8859-1\"><title>Café</title>") (Some "text/html; charset=utf-8"))
|
||||
(Some "Café")))
|
||||
;; No charset: UTF-8.
|
||||
(check (= (title-in (bytes-of "<title>Café</title>") None) (Some "Café")))
|
||||
;; A charset that nothing knows: UTF-8.
|
||||
(check (= (title-in (bytes-of "<title>Café</title>") (Some "text/html; charset=x-nothing")) (Some "Café"))))
|
||||
|
||||
(deftest "bytes that are not of the charset are read as Windows-1252"
|
||||
(def latin (string->bytes "<title>Café crème</title>" #:encoding iso-8859-1))
|
||||
(check (= (title-in latin None) (Some "Café crème")))
|
||||
(check (= (title-in latin (Some "text/html; charset=utf-8")) (Some "Café crème"))))
|
||||
|
||||
;; ---- A server on the loopback ----------------------------------------------------------
|
||||
|
||||
;; What the server answers to a path.
|
||||
;; - `status` is as the status line gives it: "200 OK".
|
||||
;; - `headers` are whole lines, without the line break.
|
||||
;; - `pieces` are written one at a time, with `pause` ms between them.
|
||||
;; - `wait` ms pass before the answer starts.
|
||||
;; - With `hold`, the body has no length and the connection stays open,
|
||||
;; after the pieces, until the server stops.
|
||||
(type (: Reply (Record (: status string)
|
||||
(: headers (Vec string))
|
||||
(: pieces (Vec (Array byte)))
|
||||
(: pause long)
|
||||
(: wait long)
|
||||
(: hold bool))))
|
||||
|
||||
(: (-> string (Vec string) (Vec (Array byte)) (#:pause long) (#:wait long) (#:hold bool) Reply))
|
||||
(defun (reply status headers pieces #:pause 0L #:wait 0L #:hold #f)
|
||||
(Reply (status status) (headers headers) (pieces pieces) (pause pause) (wait wait) (hold hold)))
|
||||
|
||||
(: (-> (Vec (Array byte)) Reply))
|
||||
(defun (html pieces) (reply "200 OK" ["Content-Type: text/html; charset=utf-8"] pieces))
|
||||
|
||||
(: (-> string Reply))
|
||||
(defun (reply-for path)
|
||||
(match path
|
||||
("/plain"
|
||||
(html [(bytes-of (str "<!doctype html><html><head><meta charset=\"utf-8\">\n"
|
||||
"<title>Tom & Jerry — Home</title></head><body>hi</body></html>"))]))
|
||||
("/moved" (reply "301 Moved Permanently" ["Location: /plain"] []))
|
||||
("/latin1"
|
||||
(reply "200 OK" ["Content-Type: text/html; charset=ISO-8859-1"]
|
||||
[(string->bytes "<html><head><title>Café crème</title></head></html>" #:encoding iso-8859-1)]))
|
||||
("/split"
|
||||
(reply "200 OK" ["Content-Type: text/html"]
|
||||
[(bytes-of "<html><head><ti") (bytes-of "tle>Split ac") (bytes-of "ross</ti") (bytes-of "tle></head>")]
|
||||
#:pause 30L))
|
||||
("/no-type" (reply "200 OK" [] [(bytes-of "<title>No type</title>")]))
|
||||
("/stalls" (reply "200 OK" ["Content-Type: text/html"] [(bytes-of "<html><head><title>Early</title>")] #:hold #t))
|
||||
("/missing" (reply "404 Not Found" ["Content-Type: text/html"] [(bytes-of "<title>Not Found</title>")]))
|
||||
("/image" (reply "200 OK" ["Content-Type: image/png"] [#[137 80 78 71]]))
|
||||
("/untitled" (html [(bytes-of "<html><head></head><body>no title</body></html>")]))
|
||||
;; The title starts after 600 KiB: after the most that is read.
|
||||
("/huge" (html [(bytes-of "<html><head>") (: (make-array 614400) (Array byte)) (bytes-of "<title>Too late</title>")]))
|
||||
("/slow" (reply "200 OK" ["Content-Type: text/html"] [(bytes-of "<title>Slow</title>")] #:wait 5000L))
|
||||
(_ (reply "404 Not Found" [] []))))
|
||||
|
||||
;; The path of the request line: "GET /plain HTTP/1.1" gives "/plain".
|
||||
(: (-> string string))
|
||||
(defun (path-of head)
|
||||
(def line (match (string-split-once head "\r\n") ((Some (Tuple l _)) l) (None head)))
|
||||
(def parts (string-split line " "))
|
||||
(if (>= (vec-length parts) 2) (vec-ref parts 1) "/"))
|
||||
|
||||
;; Reads the request's head, to its empty line, and returns its path.
|
||||
(: (-bjo-> InputPort string))
|
||||
(defbjo (request-path in)
|
||||
(let go ((seen ""))
|
||||
(if (string-contains? seen "\r\n\r\n")
|
||||
(path-of seen)
|
||||
(match (read-some in)
|
||||
((Some bs) (go (str seen (bytes->string bs))))
|
||||
(None (path-of seen))))))
|
||||
|
||||
;; Waits `ms`, or less when the server stops.
|
||||
(: (-bjo-> Listener long void))
|
||||
(defbjo (pause-for l ms)
|
||||
(ignore (sync (choose (wrap (timeout (milliseconds ms)) (fun (_) 0))
|
||||
(wrap (listener-closed l) (fun (_) 0))))))
|
||||
|
||||
;; Writes the reply. Returns the length of its body.
|
||||
(: (-bjo-> Listener OutputPort Reply int))
|
||||
(defbjo (send l out r)
|
||||
(def length (vec-fold (fun (p n) (+ n (array-length p))) 0 (.pieces r)))
|
||||
(def head (str "HTTP/1.1 " (.status r) "\r\n"
|
||||
(string-join (vec-map #(str & "\r\n") (.headers r)) "")
|
||||
(if (.hold r) "" (str "Content-Length: " (int->string length) "\r\n"))
|
||||
"Connection: close\r\n\r\n"))
|
||||
(write-bytes! out (bytes-of head))
|
||||
(flush-port out)
|
||||
(let go ((i 0))
|
||||
(when (< i (vec-length (.pieces r)))
|
||||
(when (and (> i 0) (> (.pause r) 0L)) (pause-for l (.pause r)))
|
||||
(write-bytes! out (vec-ref (.pieces r) i))
|
||||
(flush-port out)
|
||||
(go (+ i 1))))
|
||||
(when (.hold r) (ignore (sync (listener-closed l))))
|
||||
length)
|
||||
|
||||
(: (-bjo-> InputPort OutputPort void))
|
||||
(defbjo (closing in out)
|
||||
(close-input-port in)
|
||||
(close-output-port out))
|
||||
|
||||
;; One connection: one request, one reply. A client that has gone, as the
|
||||
;; client of /huge has, makes a write raise; that is not a failure here.
|
||||
(: (-bjo-> Listener InputPort OutputPort int))
|
||||
(defbjo (answer l in out)
|
||||
(def r (reply-for (request-path in)))
|
||||
(when (> (.wait r) 0L) (pause-for l (.wait r)))
|
||||
(def sent (match (try (send l out r) #:catch (System.Exception))
|
||||
((Ok n) n)
|
||||
((Err _) -1)))
|
||||
(ignore (try (closing in out) #:catch (System.Exception)))
|
||||
sent)
|
||||
|
||||
;; Accepts until the listener closes. Each connection has a fiber of its
|
||||
;; own. Returns how many there were.
|
||||
(: (-bjo-> Listener int))
|
||||
(defbjo (serve l)
|
||||
(let go ((n 0))
|
||||
(match (sync (choose (wrap (accept-evt l) Some)
|
||||
(wrap (listener-closed l) (fun (_) None))))
|
||||
((Some (Ok (Tuple in out)))
|
||||
(ignore (bjo (answer l in out)))
|
||||
(go (+ n 1)))
|
||||
((Some (Err _)) n)
|
||||
(None n))))
|
||||
|
||||
;; A port that nothing listens on: one the system gave and took back.
|
||||
(: (-bjo-> int))
|
||||
(defbjo (free-port)
|
||||
(match (tcp-listen "127.0.0.1" 0)
|
||||
((Err e) (raise e))
|
||||
((Ok l)
|
||||
(def port (listener-port l))
|
||||
(close-listener! l)
|
||||
(close-owned-or-dispose l)
|
||||
port)))
|
||||
|
||||
;; Starts a server, fetches the title of `path` from it with a deadline of
|
||||
;; `within` seconds, and stops the server.
|
||||
(: (-bjo-> string int (Result string string)))
|
||||
(defbjo (fetch-served path within)
|
||||
(match (tcp-listen "127.0.0.1" 0)
|
||||
((Err e) (Err (str "listen failed: " (.-Message e))))
|
||||
((Ok l)
|
||||
(with-open ((listening l))
|
||||
(def server (bjo (serve l)))
|
||||
(def got (fetch-title (str "http://127.0.0.1:" (int->string (listener-port l)) path) #:within within))
|
||||
(close-listener! l)
|
||||
(ignore (sync (promise-join server)))
|
||||
got))))
|
||||
|
||||
(: (-> (Result Exception (Result string string)) (Result string string)))
|
||||
(defun (joined r)
|
||||
(match r
|
||||
((Ok got) got)
|
||||
((Err e) (Err (str "raised: " (.-Message e))))))
|
||||
|
||||
;; `fetch-title` of `path` on a new server, with 3 seconds.
|
||||
(: (-> string (Result string string)))
|
||||
(defun (fetched path) (joined (sync/blocking (promise-join (bjo (fetch-served path 3))))))
|
||||
|
||||
;; `fetch-title` of `url`, with no server.
|
||||
(: (-> string (Result string string)))
|
||||
(defun (fetched-from url) (joined (sync/blocking (promise-join (bjo (fetch-title url #:within 3))))))
|
||||
|
||||
;; ---- Fetching -----------------------------------------------------------------------
|
||||
|
||||
(deftest "a page's title, fetched"
|
||||
(check (= (fetched "/plain") (Ok "Tom & Jerry — Home")))
|
||||
(check (= (fetched "/latin1") (Ok "Café crème")))
|
||||
(check (= (fetched "/split") (Ok "Split across")))
|
||||
(check (= (fetched "/no-type") (Ok "No type"))))
|
||||
|
||||
(deftest "a redirect is followed"
|
||||
(check (= (fetched "/moved") (Ok "Tom & Jerry — Home"))))
|
||||
|
||||
(deftest "reading stops at the end of the title"
|
||||
;; The server keeps the connection open after the title, past the deadline.
|
||||
(check (= (fetched "/stalls") (Ok "Early"))))
|
||||
|
||||
(deftest "why a page gives no title"
|
||||
(check (= (fetched "/missing") (Err "the server answered 404")))
|
||||
(check (= (fetched "/image") (Err "it is not a web page, but image/png")))
|
||||
(check (= (fetched "/untitled") (Err "the page has no title")))
|
||||
(check (= (fetched "/huge") (Err "the page has no title"))))
|
||||
|
||||
(deftest "a slow server meets the deadline"
|
||||
(def started (now))
|
||||
(check (= (joined (sync/blocking (promise-join (bjo (fetch-served "/slow" 1)))))
|
||||
(Err "no answer in 1 second")))
|
||||
;; The server waits 5 seconds before it answers.
|
||||
(check (< (instant->unix-milliseconds (now)) (+ (instant->unix-milliseconds started) 4000L))))
|
||||
|
||||
(deftest "a server that is not there is an Err"
|
||||
(def port (match (sync/blocking (promise-join (bjo (free-port)))) ((Ok p) p) ((Err e) (raise e))))
|
||||
(check-match (fetched-from (str "http://127.0.0.1:" (int->string port) "/")) (Err _)))
|
||||
|
||||
(deftest "only http and https are fetched"
|
||||
(check (= (fetched-from "ftp://example.org/") (Err "only http and https addresses are fetched: ftp://example.org/")))
|
||||
(check (= (fetched-from "mailto:a@example.org")
|
||||
(Err "only http and https addresses are fetched: mailto:a@example.org")))
|
||||
(check (= (fetched-from "example.org") (Err "only http and https addresses are fetched: example.org"))))
|
||||
|
||||
(run-tests)
|
||||
150
tests/wayback.bjo
Normal file
150
tests/wayback.bjo
Normal file
|
|
@ -0,0 +1,150 @@
|
|||
;; This Source Code Form is subject to the terms of the Mozilla Public
|
||||
;; License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
;; file, You can obtain one at http://mozilla.org/MPL/2.0/.
|
||||
|
||||
;; bjomarks/tests/wayback.bjo — (bjomarks wayback): the snapshot in an
|
||||
;; answer of the availability API, and the snapshot fetched from a server on
|
||||
;; the loopback, which answers as the API does.
|
||||
;;
|
||||
;; bjo run tests/wayback.bjo
|
||||
|
||||
(import (std prelude))
|
||||
(import (std test))
|
||||
(import (std datetime))
|
||||
(import (std net))
|
||||
(import (std ports))
|
||||
(import (bjomarks wayback))
|
||||
|
||||
;; ---- The snapshot in the answer ------------------------------------------------------
|
||||
|
||||
(def found
|
||||
(str "{\"url\": \"example.com\", \"archived_snapshots\": {\"closest\": {\"status\": \"200\", "
|
||||
"\"available\": true, \"url\": \"http://web.archive.org/web/20261118035140/https://example.com/\", "
|
||||
"\"timestamp\": \"20261118035140\"}}}"))
|
||||
|
||||
(def none-found "{\"url\": \"nothing.example\", \"archived_snapshots\": {}}")
|
||||
|
||||
(deftest "the snapshot in an answer"
|
||||
#:cases ((answer wanted)
|
||||
(found (Ok (Some "https://web.archive.org/web/20261118035140/https://example.com/")))
|
||||
;; An address that is https already is kept.
|
||||
("{\"archived_snapshots\": {\"closest\": {\"available\": true, \"url\": \"https://web.archive.org/web/1/x\"}}}"
|
||||
(Ok (Some "https://web.archive.org/web/1/x")))
|
||||
(none-found (Ok None))
|
||||
("{\"archived_snapshots\": {\"closest\": {\"available\": false, \"url\": \"http://web.archive.org/x\"}}}"
|
||||
(Ok None))
|
||||
("{\"archived_snapshots\": {\"closest\": {\"available\": true}}}" (Ok None))
|
||||
("{}" (Ok None))
|
||||
("[]" (Ok None)))
|
||||
(check (= (snapshot-in answer) wanted)))
|
||||
|
||||
(deftest "an answer that is not JSON is an Err"
|
||||
(check-match (snapshot-in "<html>Service Unavailable</html>") (Err _)))
|
||||
|
||||
;; ---- A server on the loopback ----------------------------------------------------------
|
||||
|
||||
;; The status, the body and the wait in ms of the answer to a request line.
|
||||
;; The page asked for is in the query: `url=` and its address, in which `:`
|
||||
;; and `/` are not encoded.
|
||||
(: (-> string (Tuple string string long)))
|
||||
(defun (answer-for line)
|
||||
(cond
|
||||
((string-contains? line "url=https://example.com/here ") (Tuple "200 OK" found 0L))
|
||||
((string-contains? line "url=https://example.com/none ") (Tuple "200 OK" none-found 0L))
|
||||
((string-contains? line "url=https://example.com/broken ") (Tuple "503 Service Unavailable" "" 0L))
|
||||
((string-contains? line "url=https://example.com/html ") (Tuple "200 OK" "<html></html>" 0L))
|
||||
((string-contains? line "url=https://example.com/slow ") (Tuple "200 OK" found 5000L))
|
||||
(else (Tuple "404 Not Found" "" 0L))))
|
||||
|
||||
;; Reads the request's head, to its empty line, and returns its first line.
|
||||
(: (-bjo-> InputPort string))
|
||||
(defbjo (request-line in)
|
||||
(let go ((seen ""))
|
||||
(if (string-contains? seen "\r\n\r\n")
|
||||
(match (string-split-once seen "\r\n") ((Some (Tuple l _)) l) (None seen))
|
||||
(match (read-some in)
|
||||
((Some bs) (go (str seen (bytes->string bs))))
|
||||
(None seen)))))
|
||||
|
||||
;; One connection: one request, one answer. The wait ends early when the
|
||||
;; server stops.
|
||||
(: (-bjo-> Listener InputPort OutputPort void))
|
||||
(defbjo (answer l in out)
|
||||
(def (Tuple status body wait) (answer-for (request-line in)))
|
||||
(when (> wait 0L)
|
||||
(ignore (sync (choose (wrap (timeout (milliseconds wait)) (fun (_) 0))
|
||||
(wrap (listener-closed l) (fun (_) 0))))))
|
||||
(def bytes (string->bytes body))
|
||||
(ignore (try (let ()
|
||||
(write-bytes! out (string->bytes (str "HTTP/1.1 " status "\r\n"
|
||||
"Content-Type: application/json\r\n"
|
||||
"Content-Length: " (int->string (array-length bytes)) "\r\n"
|
||||
"Connection: close\r\n\r\n")))
|
||||
(write-bytes! out bytes)
|
||||
(flush-port out)
|
||||
(close-input-port in)
|
||||
(close-output-port out))
|
||||
#:catch (System.Exception))))
|
||||
|
||||
;; Accepts until the listener closes.
|
||||
(: (-bjo-> Listener void))
|
||||
(defbjo (serve l)
|
||||
(match (sync (choose (wrap (accept-evt l) Some)
|
||||
(wrap (listener-closed l) (fun (_) None))))
|
||||
((Some (Ok (Tuple in out)))
|
||||
(ignore (bjo (answer l in out)))
|
||||
(serve l))
|
||||
(_ unit)))
|
||||
|
||||
;; Starts a server, asks it for the snapshot of `url` with a deadline of
|
||||
;; `within` seconds, and stops the server.
|
||||
(: (-bjo-> string int (Result string string)))
|
||||
(defbjo (fetch-served url within)
|
||||
(match (tcp-listen "127.0.0.1" 0)
|
||||
((Err e) (Err (str "listen failed: " (.-Message e))))
|
||||
((Ok l)
|
||||
(with-open ((listening l))
|
||||
(def server (bjo (serve l)))
|
||||
(def api (str "http://127.0.0.1:" (int->string (listener-port l)) "/wayback/available"))
|
||||
(def got (fetch-archive url #:within within #:api api))
|
||||
(close-listener! l)
|
||||
(ignore (sync (promise-join server)))
|
||||
got))))
|
||||
|
||||
(: (-> (Result Exception (Result string string)) (Result string string)))
|
||||
(defun (joined r)
|
||||
(match r
|
||||
((Ok got) got)
|
||||
((Err e) (Err (str "raised: " (.-Message e))))))
|
||||
|
||||
;; `fetch-archive` of `url` on a new server, with 3 seconds.
|
||||
(: (-> string (Result string string)))
|
||||
(defun (fetched url) (joined (sync/blocking (promise-join (bjo (fetch-served url 3))))))
|
||||
|
||||
;; ---- Fetching -----------------------------------------------------------------------
|
||||
|
||||
(deftest "the latest snapshot, fetched"
|
||||
(check (= (fetched "https://example.com/here")
|
||||
(Ok "https://web.archive.org/web/20261118035140/https://example.com/")))
|
||||
;; The spaces at the ends are not sent.
|
||||
(check (= (fetched " https://example.com/here ")
|
||||
(Ok "https://web.archive.org/web/20261118035140/https://example.com/"))))
|
||||
|
||||
(deftest "why there is no snapshot"
|
||||
(check (= (fetched "https://example.com/none") (Err "the Wayback Machine has no copy of this page")))
|
||||
(check (= (fetched "https://example.com/broken") (Err "the Wayback Machine answered 503")))
|
||||
(check-match (fetched "https://example.com/html") (Err _)))
|
||||
|
||||
(deftest "a slow API meets the deadline"
|
||||
(def started (now))
|
||||
(check (= (joined (sync/blocking (promise-join (bjo (fetch-served "https://example.com/slow" 1)))))
|
||||
(Err "no answer in 1 second")))
|
||||
(check (< (instant->unix-milliseconds (now)) (+ (instant->unix-milliseconds started) 4000L))))
|
||||
|
||||
(deftest "only http and https are looked up"
|
||||
(check (= (joined (sync/blocking (promise-join (bjo (fetch-archive "ftp://example.org/")))))
|
||||
(Err "only http and https addresses are looked up: ftp://example.org/")))
|
||||
(check (= (joined (sync/blocking (promise-join (bjo (fetch-archive "example.org")))))
|
||||
(Err "only http and https addresses are looked up: example.org"))))
|
||||
|
||||
(run-tests)
|
||||
Loading…
Add table
Add a link
Reference in a new issue