tavro-0.1.0.2: test/Spec.hs
module Main (main) where
import Control.Monad (filterM, forM_)
import Data.Aeson (eitherDecode)
import Data.ByteString qualified as BS
import Data.ByteString.Lazy.Char8 qualified as LBS8
import Data.IntSet qualified as IS
import Data.Text (Text)
import Data.Text qualified as T
import Data.Text.Encoding qualified as TE
import Data.Vector.Unboxed qualified as VU
import System.Directory (createDirectoryIfMissing, doesFileExist, getTemporaryDirectory, removePathForcibly)
import System.FilePath ((</>))
import Tavro.Cabal
import Tavro.Identify
import Tavro.LicenseList
import Tavro.Match
import Tavro.Regex qualified as Re
import Tavro.Spdx
import Tavro.Stack
import Tavro.Submodules
import Tavro.Template
import Tavro.Text
import Test.Hspec
import Test.QuickCheck
-- | the ends a regex reaches from the start of a text
ends :: Text -> Text -> [Int]
ends re t = case Re.compile re of
Left e -> error e
Right r -> IS.toList (Re.matchEnds r (VU.fromList (T.unpack t)) (IS.singleton 0))
fullMatch :: Text -> Text -> Bool
fullMatch re t = T.length t `elem` ends re t
keys :: Text -> [Text]
keys = tokenKeys
matches :: Text -> Text -> Bool
matches template t = case run Exactly (compileMatcher (parseTemplate (prepareTemplate template))) (subject t) of
Matched _ _ -> True
NoMatch _ _ -> False
ids :: [Hit] -> [Text]
ids = map (eId . hEntry)
fixtures :: Entry -> [FilePath]
fixtures e = ["test/fixtures/text" </> T.unpack (prefix <> eId e) <> ".txt" | prefix <- prefixes]
where
prefixes = if eDeprecated e then ["deprecated_", ""] else [""]
isInfixOf' :: String -> String -> Bool
isInfixOf' needle = T.isInfixOf (T.pack needle) . T.pack
readText :: FilePath -> IO Text
readText path = decodeLenient <$> BS.readFile path
spdxIds :: Ids
spdxIds = idsFromEntries (llEntries embedded)
main :: IO ()
main = hspec $ do
describe "Regex" $ do
it "matches literals ignoring case" $
fullMatch "Software|Materials" "software" `shouldBe` True
it "finds every end of a counted repeat" $
ends ".{0,3}" "abcdef" `shouldBe` [0, 1, 2, 3]
it "stops a repeat at the end of the text" $
ends ".+" "abc" `shouldBe` [1, 2, 3]
it "handles \\s and groups" $
fullMatch "this\\s+software\\s+and" "this software\nand" `shouldBe` True
it "lets a space match any run of whitespace" $ do
fullMatch "SOFTWARE IS|MATERIALS ARE" "software\n is" `shouldBe` True
fullMatch "a b" "a\t\tb" `shouldBe` True
it "keeps case-insensitive negated classes negated" $
fullMatch "[^a]" "A" `shouldBe` False
it "handles optional groups" $
ends "(([0-9]+)\\.([0-9]+))?" "1.2" `shouldBe` [0, 3]
it "handles classes with ranges and escapes" $
fullMatch "CeCILL[¹1]?( \\(?for Ce[\\[\\(]a[\\]\\)])?" "cecill1 (for Ce[a]" `shouldBe` True
it "matches an empty alternative" $
ends ",|" "," `shouldBe` [0, 1]
it "rejects lookaround, which the license list doesn't use" $
either (const True) (const False) (Re.compile "(?=a)") `shouldBe` True
it "agrees with a naive matcher on .{m,n}" $
property $ \(NonNegative m) (NonNegative k) (ASCIIString s) ->
let n = m + k `mod` 5
re = T.pack (".{" <> show m <> "," <> show n <> "}")
in ends re (T.pack s) === [i | i <- [m .. n], i <= length s]
describe "Text" $ do
it "ignores case and whitespace" $
keys "Hello World" `shouldBe` keys "hello\n\tworld"
it "treats quotes, dashes and the copyright symbols alike" $ do
keys "“so-called” ‘x’" `shouldBe` keys "\"so—called\" 'x'"
keys "©" `shouldBe` keys "(c)"
keys "(c)" `shouldBe` keys "Copyright"
it "knows varietal spellings" $ do
keys "licence" `shouldBe` keys "license"
keys "the copyright owner" `shouldBe` keys "the copyright holder"
keys "per cent" `shouldBe` keys "percent"
keys "sub license" `shouldBe` keys "sublicense"
it "treats http and https alike" $
keys "http://example.com" `shouldBe` keys "https://example.com"
it "drops comment markers" $
keys "/*\n * Permission is granted\n */" `shouldBe` keys "Permission is granted"
it "drops separator lines" $
keys "Terms\n-----------\nmore" `shouldBe` keys "Terms more"
it "keeps offsets into the original text" $
property $
\(ASCIIString s) -> T.length (prepare (T.pack s)) === length s
it "ignores a byte order mark" $
keys "\xFEFFPermission granted" `shouldBe` keys "Permission granted"
it "splits punctuation into tokens of its own" $
keys "a,b." `shouldBe` ["a", ",", "b", "."]
describe "Template" $ do
it "parses vars" $
parseTemplate "a <<var;name=\"x\";original=\"y\";match=\".+\">> b"
`shouldBe` [Lit "a ", Var "x" "y" ".+", Lit " b"]
it "parses nested optionals" $
parseTemplate "a <<beginOptional>>b <<beginOptional>>c d<<endOptional>><<endOptional>>"
`shouldBe` [Lit "a ", Choice [[Lit "b ", Choice [[Lit "c d"], []]], []]]
it "keeps quotes inside a match" $
parseTemplate "<<var;name=\"q\";original=\"\";match=\"\"x\"|y\">>"
`shouldBe` [Var "q" "" "\"x\"|y"]
it "takes a literal < before a tag" $
parseTemplate "<<beginOptional>><<<endOptional>> x"
`shouldBe` [Choice [[Lit "<"], []], Lit " x"]
it "closes an unclosed optional at the end" $
parseTemplate "a <<beginOptional>>b c" `shouldBe` [Lit "a ", Choice [[Lit "b c"], []]]
it "turns an optional word ending into a choice of words" $
parseTemplate "the license<<beginOptional>>s<<endOptional>> here"
`shouldBe` [Lit "the ", Choice [[Lit "licenses"], [Lit "license s"], [Lit "license"]], Lit " here"]
it "moves punctuation in the middle of a word into the choice" $
parseTemplate "reasonable attorney<<beginOptional>>'<<endOptional>>s fees"
`shouldBe` [Lit "reasonable ", Choice (map (\x -> [Lit x]) ["attorney's", "attorney' s", "attorney 's", "attorney ' s", "attorneys", "attorney s"]), Lit " fees"]
it "leaves a choice with whitespace in it alone" $
parseTemplate "License<<beginOptional>> version 2<<endOptional>>cover"
`shouldBe` [Lit "License", Choice [[Lit " version 2"], []], Lit "cover"]
describe "Match" $ do
let t = "<<beginOptional>>Title<<endOptional>> <<var;name=\"c\";original=\"\";match=\".{0,50}\">> Permission is granted, to <<var;name=\"w\";original=\"anyone\";match=\"anyone|everyone\">> ."
it "matches the original" $
matches t "Title\n\nPermission is granted, to anyone." `shouldBe` True
it "lets optional text be left out" $
matches t "Permission is granted, to anyone." `shouldBe` True
it "lets a var take its alternatives" $
matches t "Copyright 2024 Someone\nPermission is granted, to everyone." `shouldBe` True
it "refuses text a var doesn't allow" $
matches t "Permission is granted, to nobody." `shouldBe` False
it "refuses extra text" $
matches t "Permission is granted, to anyone. And also more." `shouldBe` False
it "refuses a var longer than its regex allows" $
matches t (T.replicate 60 "x " <> "Permission is granted, to anyone.") `shouldBe` False
it "finds a license inside a larger text" $
case run Within (compileMatcher (parseTemplate t)) (subject "int x;\n/* Permission is granted, to anyone. */\nint y;") of
-- int x ; are tokens 0 to 2, and /* is dropped
Matched a b -> (a, b) `shouldBe` (3, 10)
r -> expectationFailure (show r)
describe "identify" $ do
it "says MIT is MIT" $ do
mit <- readText "test/fixtures/text/MIT.txt"
ids (identify defaultOptions embedded mit) `shouldBe` ["MIT"]
it "finds a license in a source header" $ do
apache <- readText "test/fixtures/text/Apache-2.0.txt"
let header = "// Licensed under the Apache License, Version 2.0 (the \"License\");\n"
let src = "#include <stdio.h>\n" <> header <> "int main(void) { return 0; }\n"
ids (identify defaultOptions embedded (apache <> "\n" <> src)) `shouldContain` ["Apache-2.0"]
it "matches a license with a byte order mark and rewrapped lines" $ do
mit <- readText "test/fixtures/text/MIT.txt"
let rewrapped = T.replace "SOFTWARE IS" "SOFTWARE\nIS" mit
ids (identify defaultOptions embedded ("\xFEFF" <> rewrapped)) `shouldBe` ["MIT"]
it "doesn't stretch a var over concatenated licenses" $ do
texts <- mapM (\f -> readText ("test/fixtures/text/" <> f <> ".txt")) ["X11", "Apache-2.0", "curl"]
let hits = identify defaultOptions embedded (T.intercalate "\n" texts)
map (\h -> (eId (hEntry h), hHow h)) hits `shouldBe` [("X11", Inside), ("Apache-2.0", Inside), ("curl", Inside)]
it "finds nothing in text that isn't a license" $
ids (identify defaultOptions embedded "hello, this is a readme\n") `shouldBe` []
describe "Cabal" $ do
let unit i n c ds local =
"{\"type\":\"configured\",\"id\":\""
<> i
<> "\",\"pkg-name\":\""
<> n
<> "\",\"pkg-version\":\"1.0\""
<> maybe "" (\x -> ",\"component-name\":\"" <> x <> "\"") c
<> ",\"style\":\""
<> (if local then "local" else "global")
<> "\",\"depends\":["
<> LBS8.intercalate "," (map (\d -> "\"" <> d <> "\"") ds)
<> "],\"exe-depends\":[\"happy-1\"]}"
planOf us = "{\"compiler-id\":\"ghc-9.10.3\",\"install-plan\":[" <> LBS8.intercalate "," us <> "]}"
plan =
either error id . eitherDecode . planOf $
[ unit "app-exe" "app" (Just "exe:app") ["lib-a", "base"] True,
unit "app-test" "app" (Just "test:app-test") ["hspec"] True,
unit "lib-a" "a" (Just "lib") ["lib-b"] False,
unit "lib-b" "b" (Just "lib") [] False,
unit "base" "base" Nothing [] False,
unit "hspec" "hspec" (Just "lib") [] False,
unit "happy-1" "happy" (Just "exe:happy") [] False
]
names = fmap (map uName)
it "follows library dependencies from the executables" $
names (linkedUnits [] plan) `shouldBe` Right ["app", "base", "a", "b"]
it "leaves out test suites and build tools" $
names (linkedUnits [] plan) `shouldSatisfy` either (const False) (\ns -> "hspec" `notElem` ns && "happy" `notElem` ns)
it "takes a component when asked" $
names (linkedUnits ["test:app-test"] plan) `shouldBe` Right ["app", "hspec"]
it "says which components there are when one isn't" $
linkedUnits ["exe:nope"] plan `shouldSatisfy` either ("exe:app" `isInfixOf'`) (const False)
it "knows Cabal's old license names" $ do
legacyLicense "BSD3" `shouldBe` Just "BSD-3-Clause"
legacyLicense "GPL-3" `shouldBe` Just "GPL-3.0-only"
legacyLicense "AllRightsReserved" `shouldBe` Just "NONE"
legacyLicense "OtherLicense" `shouldBe` Nothing
it "spots license files" $ do
map isLicenseFile ["LICENSE", "LICENSE-MIT", "COPYING.LIB", "mit-license.txt", "README.md", "Setup.hs"]
`shouldBe` [True, True, True, True, False, False]
let pkg = Package "p" "1.0" False ["p-1.0"] Nothing
judged declared files = judge spdxIds (PackageLicense pkg declared (map fst files)) files
it "reports the declared license" $
vExpression (judged (Just "MIT") [("LICENSE", [["MIT"]])]) `shouldBe` "MIT"
it "warns when the license file says something else" $
vNotes (judged (Just "BSD-3-Clause") [("LICENSE", [["BSD-2-Clause"]])]) `shouldSatisfy` (not . null)
it "goes by the text when the declared license isn't SPDX" $
vExpression (judged (Just "OtherLicense") [("LICENSE", [["MIT"]])]) `shouldBe` "MIT"
it "converts old license names" $
vExpression (judged (Just "BSD3") []) `shouldBe` "BSD-3-Clause"
it "won't pick between texts that read the same" $
vExpression (judged (Just "OtherLicense") [("COPYING", [["GPL-2.0-only", "GPL-2.0-or-later"]])]) `shouldBe` "LicenseRef-OtherLicense"
it "turns names that aren't SPDX into LicenseRefs, like Cabal" $ do
vExpression (judged (Just "PublicDomain") []) `shouldBe` "LicenseRef-PublicDomain"
vExpression (judged (Just "LGPL-2") []) `shouldBe` "LicenseRef-LGPL-2"
vExpression (judged (Just "AllRightsReserved") []) `shouldBe` "NONE"
vExpression (judged Nothing []) `shouldBe` "NOASSERTION"
it "replaces deprecated GNU ids" $ do
let v = judged (Just "GPL-2.0+ OR GPL-3.0") [("COPYING", [["GPL-2.0-only", "GPL-2.0-or-later"]])]
vExpression v `shouldBe` "GPL-2.0-or-later OR GPL-3.0-only"
vNotes v `shouldBe` []
it "keeps an exception with its license" $
vExpression (judged (Just "OtherLicense") [("LICENSE", [["Apache-2.0"], ["LLVM-exception"]])]) `shouldBe` "Apache-2.0 WITH LLVM-exception"
describe "Submodules" $ do
it "parses git submodule status, nested and not checked out ones too" $
parseSubmoduleStatus
( T.unlines
[ " 1111 vendor/a (v1.0)",
"+2222 vendor/a/deps/b c (heads/main)",
"-3333 vendor/missing",
" 4444 vendor/undescribed"
]
)
`shouldBe` ( [ Submodule "vendor/a" "1111",
Submodule "vendor/a/deps/b c" "2222",
Submodule "vendor/undescribed" "4444"
],
["vendor/missing"]
)
let sub = Submodule "vendor/a" "1111"
judgeSub = judgeSubmodule spdxIds
it "takes the license from the license file" $
vExpression (judgeSub sub [("LICENSE", [["MIT"]])]) `shouldBe` "MIT"
it "joins several license files with AND, and notes it might be OR" $ do
let v = judgeSub sub [("LICENSE-MIT", [["MIT"]]), ("LICENSE-APACHE", [["Apache-2.0"]])]
vExpression v `shouldBe` "Apache-2.0 AND MIT"
vNotes v `shouldSatisfy` (not . null)
it "puts an exception after its license with WITH" $ do
vExpression (judgeSub sub [("LICENSE.TXT", [["Apache-2.0"], ["LLVM-exception"]])]) `shouldBe` "Apache-2.0 WITH LLVM-exception"
vExpression (judgeSub sub [("LICENSES/Apache-2.0.txt", [["Apache-2.0"]]), ("LICENSES/LLVM-exception.txt", [["LLVM-exception"]])])
`shouldBe` "Apache-2.0 WITH LLVM-exception"
it "doesn't guess which license an exception goes with" $
vExpression (judgeSub sub [("LICENSE", [["Apache-2.0"], ["MIT"], ["LLVM-exception"]])]) `shouldBe` "NOASSERTION"
it "doesn't guess between licenses the text can't tell apart" $
vExpression (judgeSub sub [("COPYING", [["GPL-2.0-only", "GPL-2.0-or-later"]])]) `shouldBe` "NOASSERTION"
it "says when there's no license file" $ do
let v = judgeSub sub []
vExpression v `shouldBe` "NOASSERTION"
vNotes v `shouldSatisfy` (not . null)
describe "Stack" $ do
let deps =
either error id . parseDependencies $
"[{\"name\":\"app\",\"version\":\"1.0\",\"license\":\"MIT\",\"dependencies\":[\"vector\",\"base\"],"
<> "\"location\":{\"type\":\"project package\",\"url\":\"file:///src/app/\"}},"
<> "{\"name\":\"vector\",\"version\":\"0.13\",\"license\":\"BSD3\",\"dependencies\":[\"base\",\"tasty\"],"
<> "\"location\":{\"type\":\"hackage\",\"url\":\"https://hackage.haskell.org/package/vector-0.13\"}},"
<> "{\"name\":\"tasty\",\"version\":\"1.5\",\"license\":\"MIT\",\"dependencies\":[\"base\"]},"
<> "{\"name\":\"base\",\"version\":\"4.20\",\"license\":\"BSD-3\",\"dependencies\":[]}]"
conf i n v ds = "name: " <> n <> "\nversion: " <> v <> "\nid: " <> i <> "\nlicense: BSD-3-Clause\ndepends:\n " <> T.unwords ds <> "\n"
withDb confs act = do
tmp <- getTemporaryDirectory
let db = tmp </> "tavro-test-db"
removePathForcibly db
createDirectoryIfMissing True db
forM_ confs $ \(i, c) -> BS.writeFile (db </> T.unpack i <> ".conf") (TE.encodeUtf8 c)
r <- act db
removePathForcibly db
pure r
names = map (\p -> (pName p, pInProject p))
it "reads stack ls dependencies json" $
map sdProjectDir deps `shouldBe` [Just "/src/app/", Nothing, Nothing, Nothing]
it "follows installed libraries' own dependencies, not stack's wider graph" $ do
ps <- withDb [("vector-0.13-x", conf "vector-0.13-x" "vector" "0.13" ["base-4.20"]), ("base-4.20", conf "base-4.20" "base" "4.20" [])] $ \db ->
stackPackages [db] deps
names ps `shouldBe` [("app", True), ("base", False), ("vector", False)]
it "falls back on stack's graph for what isn't built" $ do
ps <- withDb [] $ \db -> stackPackages [db] deps
names ps `shouldBe` [("app", True), ("base", False), ("tasty", False), ("vector", False)]
describe "the required keys worked out at build time" $
it "are what compiling each template gives" $
forM_ (llEntries embedded) $ \e -> do
(eId e, eRequired e) `shouldBe` (eId e, matcherRequired (eMatcher e))
forM_ (eHeader e) $ \(required, m) -> (eId e, required) `shouldBe` (eId e, matcherRequired m)
-- what Spdx-Java-Library's own tests check: each license's reference text
-- from license-list-data matches the license's own template
describe "every license matches its own text" $
forM_ (llEntries embedded) $ \e ->
it (T.unpack (eId e)) $ do
found <- filterM doesFileExist (fixtures e)
case found of
[] -> expectationFailure ("no reference text at " <> unwords (fixtures e))
path : _ -> do
txt <- readText path
case explain e txt of
Matches -> pure ()
x -> expectationFailure (show x)