A peer-to-peer stack for code collaboration
Make it possible to run rad/monadic tests stand alone
Thomas Scholtesee9049dc2d02
diff --git a/cloudbuild.yaml b/cloudbuild.yamlindex 4fa4b7f..043a4df 100644--- a/cloudbuild.yaml+++ b/cloudbuild.yaml@@ -48,7 +48,7 @@ steps:apt-get -yqq install libpq-devstack build --fast --test --no-terminal --pedantic- stack exec -- radicle test/prelude.rad+ stack exec -- radicle test/all.rad./images/radicle-server/ci-copy-bin.shdiff --git a/docs/source/reference.rst b/docs/source/reference.rstindex 5d2574d..59b33c9 100644--- a/docs/source/reference.rst+++ b/docs/source/reference.rst@@ -420,6 +420,13 @@ Given an ISO 8601 formatted Coordinated Universal Time (UTC) timestamp,returns the corresponding Unix epoch time, i.e., the number of secondssince Jan 01 1970 (UTC).+``from-unix-epoch``+~~~~~~~~~~~~~~~~~~~++Given an integer the represents seconds from the unix epock return an+ISO 8601 formatted Coordinated Universal Time (UTC) timestamp+representing that time.+``now!``~~~~~~~~@@ -860,6 +867,18 @@ List the contents of the current working directoryModified the value stored in a file according to the function ``f``.+``(install-fake-filesystem! files)``+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~++Installs a fake for ``read-file!`` that simulates the presence of files+in the ``files`` dictionary.++If+``(read-file! path) is called and``\ path\ ``is a key in``\ files\ ``then the value from``\ files\ ``is returned. Otherwise the original``\ read-file!\`+is used.++This requires the ``prelude/test/primitive-stub`` script to be loaded.+``prelude/bool``----------------diff --git a/rad/monadic/issues.rad b/rad/monadic/issues.radindex 5c64a00..6e2d11b 100644--- a/rad/monadic/issues.rad+++ b/rad/monadic/issues.rad@@ -6,6 +6,8 @@(import prelude/lens :unqualified)(import prelude/chain '[send-code! ]:unqualified)+(import prelude/time '[install-fake-clock] :unqualified)+(import prelude/io :as 'io)(def radicle-issues-chain-id"The name of this chain."@@ -190,7 +192,12 @@(:test"The monadic issues chain works."[:setup- (do (def chain-name "http://localhost:8000/chains/fxoo")+ (do (chain/install-remote-chain-fake)+ (install-fake-clock)+ (io/install-fake-filesystem!+ { "my-keys.rad" (show (gen-key-pair! (default-ecc-curve)))+ })+ (def chain-name (string-append "http://foo"))(def chain (ref (chain/new-chain chain-name)))(create-issues-chain! chain-name)(simple-create-issue! chain "title0" "body0")@@ -199,13 +206,13 @@(simple-add-comment! chain 1 "comment1")(simple-edit-issue! chain 0 {:state :closed})(simple-edit-comment! chain 0 0 {:body "comment0-edit"})- (def t (now!))+ (def last-checked-at (now!))(simple-create-issue! chain "new" "new")(simple-create-issue! chain "newer" "newer")(simple-add-comment! chain 0 "new")(fetch! chain)(def is (list-issues chain))- (def new (recent-activity chain t)))]+ (def new (recent-activity chain last-checked-at)))][ (length (seq is)) ==> 4 ][ (view (.. (@ 0) (@ :title)) is) ==> "title0" ][ (view (.. (@ 1) (@ :title)) is) ==> "title1" ]diff --git a/rad/monadic/names.rad b/rad/monadic/names.radindex 6041331..744631a 100644--- a/rad/monadic/names.rad+++ b/rad/monadic/names.rad@@ -30,7 +30,8 @@(:test"The monadic name chain works."[:setup- (do (def chain-name "http://localhost:8000/chains/shkjksa")+ (do (chain/install-remote-chain-fake)+ (def chain-name "http://localhost:8000/chains/shkjksa")(create-name-chain! chain-name)(add-name! chain-name "alice" "a")(add-name! chain-name "bob" "b")diff --git a/rad/prelude.rad b/rad/prelude.radindex 52ac968..304f1ea 100644--- a/rad/prelude.rad+++ b/rad/prelude.rad@@ -18,6 +18,7 @@(file-module! "rad/prelude/state-machine.rad")(file-module! "rad/prelude/validation.rad")(file-module! "rad/prelude/util.rad")+(file-module! "rad/prelude/time.rad")(file-module! "rad/prelude/test.rad")(import prelude/basic :unqualified)diff --git a/rad/prelude/io.rad b/rad/prelude/io.radindex 8921024..e56c209 100644--- a/rad/prelude/io.rad+++ b/rad/prelude/io.rad@@ -3,6 +3,7 @@:exports '[print! shell! process! read-line! read-file-value! read-file-values!shell-with-stdout! shell-no-stdin! process-with-stdout! write-file!init-file-dict! read-file-key! write-file-key! ls! modify-file!+ install-fake-filesystem!]}(import prelude/patterns :unqualified)@@ -192,3 +193,23 @@ Example: `(process! \"ls\" [\"-Glah\"] \"\")`. ""Read a file key. Assumes that the file contents is a serialised dict."(fn [file k](lookup-maybe k (read-file-value! file))))++(def install-fake-filesystem!+ "Installs a fake for `read-file!` that simulates the presence of+ files in the `files` dictionary.++ If `(read-file! path) is called and `path` is a key in `files` then+ the value from `files` is returned. Otherwise the original+ `read-file!` is used.++ This requires the `prelude/test/primitive-stub` script to be loaded."+ (fn [files]+ (def original-read-file! (read-ref primitive-stub-ref/read-file!))+ (def read-file+ (fn [path]+ (if (member? path files)+ (lookup path files)+ (original-read-file! path))+ ))+ (write-ref primitive-stub-ref/read-file! read-file)+ ))diff --git a/rad/prelude/time.rad b/rad/prelude/time.radnew file mode 100644index 0000000..3a420f8--- /dev/null+++ b/rad/prelude/time.rad@@ -0,0 +1,19 @@+{:module 'prelude/time+ :doc "Time-related functions."+ :exports '[install-fake-clock+ ]}++(def install-fake-clock+ "Install a fake, monotonic implementation for the `now!` primitive.+ Every call to `now!` advances the clock by one second.+ This requires the `prelude/test/primitive-stub` script to be loaded."+ (fn []+ (def current-time (ref 0))+ (def now!+ (fn []+ (def t (read-ref current-time))+ (write-ref current-time (+ 1 t))+ (from-unix-epoch t)+ ))+ (write-ref primitive-stub-ref/now! now!)+ ))diff --git a/rad/tests/stub-primitives.rad b/rad/tests/stub-primitives.radindex 0719038..1b448b2 100644--- a/rad/tests/stub-primitives.rad+++ b/rad/tests/stub-primitives.rad@@ -1,7 +1,7 @@;; This script stubs some primitives for code evaluated afterwards.;;;; This code is used by `rad/tests/run.rad` to test code that relies on-;; primitives. Currently only the `send!` and `receive!` primitives are stubbed.+;; primitives. Currently only some primitives are stubbed.;;;; A primitive `prim` is stubbed by creating a ref `primitive-stub-ref/prim`;; that holds the original primitive value. The function `prim` is then@@ -19,3 +19,13 @@(def machine/eval-server/get-log!(fn [a b] ((read-ref primitive-stub-ref/receive!) a b)))++;; now!+(def primitive-stub-ref/now! (ref now!))+(def now!+ (fn [] ((read-ref primitive-stub-ref/now!))))++;; read-file!+(def primitive-stub-ref/read-file! (ref read-file!))+(def read-file!+ (fn [path] ((read-ref primitive-stub-ref/read-file!) path)))diff --git a/reference-doc.yaml b/reference-doc.yamlindex 73494a4..75e7d5e 100644--- a/reference-doc.yaml+++ b/reference-doc.yaml@@ -93,6 +93,7 @@ primFns:# Time- timestamp?- unix-epoch+- from-unix-epoch- now!# JSON- to-jsondiff --git a/src/Radicle/Internal/Number.hs b/src/Radicle/Internal/Number.hsindex db3f163..d8fb5c4 100644--- a/src/Radicle/Internal/Number.hs+++ b/src/Radicle/Internal/Number.hs@@ -2,7 +2,7 @@ module Radicle.Internal.Number whereimport Protolude-import Data.Scientific (Scientific, fromRationalRepetendUnlimited)+import qualified Data.Scientific as ScientificisInteger :: Rational -> Either Text IntegerisInteger (a :% b) | b == 1 = pure a@@ -18,7 +18,13 @@ isInt x = isInteger x >>= intfromIntegral (minBound :: Int) <= i&& i <= fromIntegral (maxBound :: Int)-isSci :: Rational -> Either Text Scientific-isSci r = case fromRationalRepetendUnlimited r of+toBoundedInteger :: (Integral i, Bounded i) => Rational -> Maybe i+toBoundedInteger r =+ case isSci r of+ Left _ -> Nothing+ Right s -> Scientific.toBoundedInteger s++isSci :: Rational -> Either Text Scientific.Scientific+isSci r = case Scientific.fromRationalRepetendUnlimited r of(s, Nothing) -> pure s_ -> Left "Does not have a non-repeating decimal expansion"diff --git a/src/Radicle/Internal/PrimFns.hs b/src/Radicle/Internal/PrimFns.hsindex e97e0f6..9dc88df 100644--- a/src/Radicle/Internal/PrimFns.hs+++ b/src/Radicle/Internal/PrimFns.hs@@ -643,10 +643,20 @@ purePrimFns = fromList $ allDocs $, oneArg "unix-epoch" $ \caseString s -> doutc <- Time.parseTime s ?? toLangError (OtherError "Invalid UTC timestamp.")- ss <- Time.unixSeconds utc ?? toLangError (OtherError "Could not convert UTC time to Unix epoch.")+ let ss = Time.unixSeconds utcpure (Number (fromIntegral ss))v -> throwErrorHere $ TypeError "unix-epoch" 0 TString v)+ , ( "from-unix-epoch"+ , "Given an integer the represents seconds from the unix epock return an \+ \ ISO 8601 formatted Coordinated Universal Time (UTC) timestamp representing\+ \ that time."+ , oneArg "from-unix-epoch" $ \case+ Number q -> case Num.toBoundedInteger q of+ Nothing -> throwErrorHere $ OtherError "from-unix-epoch: argument must be an int64"+ Just n -> pure $ String $ Time.formatTime $ Time.unixSecondsToUtc n+ v -> throwErrorHere $ TypeError "from-unix-epoch" 0 TNumber v+ )]whereisTy t = "Checks if the argument is a " <> t <> "."diff --git a/src/Radicle/Internal/Time.hs b/src/Radicle/Internal/Time.hsindex bd90f32..a9e2711 100644--- a/src/Radicle/Internal/Time.hs+++ b/src/Radicle/Internal/Time.hs@@ -4,6 +4,7 @@ import qualified Preludeimport Protoludeimport qualified Data.Time as Time+import qualified Data.Time.Clock.System as Timelocale :: Time.TimeLocalelocale = Time.defaultTimeLocale@@ -17,9 +18,8 @@ parseTime = Time.parseTimeM False locale fmt . toSformatTime :: Time.UTCTime -> TextformatTime = toS . Time.formatTime locale fmt-unixSeconds :: Time.UTCTime -> Maybe Int-unixSeconds utc =- let secs = Time.formatTime Time.defaultTimeLocale "%s" utc- in case readEither secs of- Left _ -> Nothing- Right (i :: Int) -> pure $ fromIntegral i+unixSeconds :: Time.UTCTime -> Int64+unixSeconds utc = Time.systemSeconds $ Time.utcToSystemTime utc++unixSecondsToUtc :: Int64 -> Time.UTCTime+unixSecondsToUtc seconds = Time.systemToUTCTime $ Time.MkSystemTime seconds 0diff --git a/test/prelude.rad b/test/all.radsimilarity index 83%rename from test/prelude.radrename to test/all.radindex 3f29344..e90878c 100755--- a/test/prelude.rad+++ b/test/all.rad@@ -5,6 +5,8 @@(load! "rad/tests/stub-primitives.rad")(load! "rad/prelude.rad")+(load! "rad/monadic/issues.rad")+(load! "rad/monadic/names.rad")(import prelude/test)diff --git a/test/spec/Radicle/Internal/TestCapabilities.hs b/test/spec/Radicle/Internal/TestCapabilities.hsindex c91d8d0..2522940 100644--- a/test/spec/Radicle/Internal/TestCapabilities.hs+++ b/test/spec/Radicle/Internal/TestCapabilities.hs@@ -1,17 +1,13 @@-- | This module defines instances for the classes in-- Radicle.Internal.Subscriber.Capabilities that may be used for testing.module Radicle.Internal.TestCapabilities (- runCode- , runCodeWithWorld+ runCodeWithWorld, runPureCode, runCodeWithInput, runCodeWithFiles- , runCodeWithSourceFiles, WorldState(..), defaultWorldState- , worldStateWithSource- , addFileToWorld) whereimport Protolude hiding (TypeError)@@ -57,15 +53,8 @@ worldStateWithSource = dosources <- sourceFilespure $ defaultWorldState { worldStateFiles = sources }-addFileToWorld :: Text -> Text -> WorldState -> WorldState-addFileToWorld name contents ws = ws { worldStateFiles = Map.insert name contents (worldStateFiles ws) }-type TestLang = Lang (StateT WorldState IO)--- | Run Radicle code in a REPL environment.-runCode :: Text -> IO (Either (LangError Value) Value)-runCode code = fst <$> runCodeWithWorld defaultWorldState code--- | Run Radicle code in a REPL environment, with all library files-- readable, and with the provided stdin lines.--@@ -83,13 +72,6 @@ runCodeWithFiles files code =let ws = defaultWorldState { worldStateFiles = files }in fst <$> runCodeWithWorld ws code--- | Run Radicle code in a REPL environment with all Radicle source files--- readable.-runCodeWithSourceFiles :: Text -> IO (Either (LangError Value) Value)-runCodeWithSourceFiles code = do- ws <- worldStateWithSource- fst <$> runCodeWithWorld ws code--- | Run radicle code in a pure environment.runPureCode :: Text -> Either (LangError Value) ValuerunPureCode code =diff --git a/test/spec/Radicle/Tests.hs b/test/spec/Radicle/Tests.hsindex fb5a106..e3a9273 100644--- a/test/spec/Radicle/Tests.hs+++ b/test/spec/Radicle/Tests.hs@@ -834,50 +834,6 @@ test_cbor =<> "\nGot\n\t" <> show gotcounterexample info $ got == expected---- | Call @(run-all-tests)@ which runs all tests defined in the--- Radicle source with the @:test@ macro.-test_source_files :: IO TestTree-test_source_files = do- tests <- testFiles ["rad/monadic/issues.rad", "rad/monadic/names.rad"]- pure $ testGroup "Radicle source file tests" tests- where- testFiles :: [FilePath] -> IO [TestTree]- testFiles files = do- ws' <- worldStateWithSource- keyPair :: Text <- runCode "(gen-key-pair! (default-ecc-curve))" >>= \case- Right kp -> pure $ renderCompactPretty kp- Left _ -> panic "Couldn't generate keypair file."- let ws = addFileToWorld "my-keys.rad" keyPair ws'- let loads = T.unlines [ "(load! \"" <> toS file <> "\")" | file <- files ]- let code = "(load! \"rad/tests/stub-primitives.rad\")"- <> "(load! \"rad/prelude.rad\")"- <> loads- <> "(import prelude/test)"- <> "(prelude/test/run-all (read-ref tests))"- (r, out) <- runCodeWithWorld ws $ toS code- let doesntThrow = if isRight r- then pure ()- else assertFailure $ "Expected Right, got: " <> toS (prettyEither r)- pure $ testCase "doesn't throw" doesntThrow : makeTests (reverse out)-- -- | Takes an output generated by the @:test@ macro and turns it into- -- a 'TestTree' that passes if the macro test passes.- makeTests :: [Text] -> [TestTree]- makeTests lines = do- line <- lines- if- | "ok" `T.isPrefixOf` line ->- pure $ testCase (drop 2 $ toS line) $ pure ()- | "not ok" `T.isPrefixOf` line ->- pure $ testCase (drop 6 $ toS line) $ assertFailure "failed"- | otherwise -> mzero--test_counter :: TestTree-test_counter = testCase "rad/examples/counter.rad" $ do- res <- runCodeWithSourceFiles "(load! \"rad/examples/counter.rad\") (counter/run-test)"- res @?= Right (kw "test-ok")-test_macros :: [TestTree]test_macros =[ testCase ":enter-chain keeps old bindings" $ do