Files
simplex-chat/tests/Bots/StoreService/NamesCodesTests.hs
T
ad75fe706f store: sell and register SimpleX names (#7979)
* core: add prepaid name codes and length bounds

* store: run the names migration after badges

* store: issue and revoke prepaid name codes

* store: document issuing prepaid name codes

* store: move the ABI helpers to Names.Abi

* store: read the [names] and [chain] settings

* store: add the names chain client and reads

* store: refuse group name codes while names are off

* store: search names and preview links

* store: serve each site on its own port

* scripts: deploy the badges and names sites

* store: document search and the two sites

* store: add the drop_taken_codes migration

* store: read the names codes_only setting

* store: add the names store and order signatures

* store: take name orders by card, crypto or code

* store: document name orders and codes-only

* store: add the names transaction sender

* store: commit and register queued orders

* store: reveal and retry an owner's order

* store: document the gas key

* store: add the name balance migrations

* store: read crypto units, rates and confirmations

* store: keep a taken order's money as a balance

* store: spend a balance on another name

* store: record refunds with //refund

* store: document balances and refunds

* store: add the agreed terms migration

* store: read the terms and community names

* store: answer community and terms in search

* store: sign and store the agreed terms

* store: document the terms and community names

* store: add the invoiced units migration

* store: read the crypto an invoice asks

* store: credit late and overpaid crypto by share

* store: document crediting late crypto by share

* store: add the record changes migration

* store: find an owner's orders and move one

* store: relay owners' link edits on chain

* store: document link edits

* store: move isLoopbackHost to Config

* store: trust dev issuer keys on the local chain

* scripts: build the names site from a submodule

* scripts: add the dev setup and contract run

* store: document the dev setup and names image

* store: send a Stripe idempotency key for names

* tests: wait until a relay lets go of its edit

* store: refuse a link edit deadline under 10 min

* store: count reverted link edits in the year limit

* store: require https for a remote chain node

* store: refuse zero chain confirmations

* store: set up the dev stack from the names branch

* store: rerun a failed unpaid cleanup next pass

* store: never replace a succeeded Stripe intent

* store: refuse an ini setting written as key: value

* store: note the webapp submodule's pinned branch

* store: document confirmLanded judging by ownerOf

* store: update the names webapp submodule

* store-service: register names under the name policy, every name accepting its terms on chain (#7889)

* store: accept each name's terms on chain under the name policy

* ci: run the reduced build on sh/names-deploy

* store: address review: policy re-read, terms reads and startup log

* store: never credit an unconfirmed extra

* store: alert money sent to a paid name invoice

* store: refuse to start on another chain's node

* store: keep orders while the allowance is used up

* store: replace a stalled transaction after 3 blocks

* store: judge a name taken at confirmation depth

* store: bind the template's listener to loopback

* store: scan only the ids of active name orders

* store: refuse unknown [names] and [chain] settings

* store: fetch the webapp submodule in upgrade steps

* store: delete definitions only tests use

* store: lock only name invoices at settlement

* store: retry an unexpired commitment as usual

* store: share the helpers defined twice

* store: test route limits on the running service

* store: fix tests that could not fail

* ci: test the store service on Postgres

* store: count IPv6 clients by their /64

* store: sweep invoices read alone past a list cap

* store: cap checkouts of all clients together

* store: cap the long polls held at once

* store: stop the old badge project at upgrade

* store: keep search lookups free of previews

* store: read the ini as UTF-8 in any locale

* ci: run Postgres store tests in a UTF-8 locale

* store: cap the transactions one order sends

* store: cancel a card intent after three declines

* store: refuse a name price under a cent

* store: send each transaction with gas headroom

* store: cap searches and read terms once per block

* store: never log the group join link

* store: mask the database password at startup

* store: run one instance per database

* store: limit name codes to admins, 100 a day

* store: refuse HighSpeed settlement with names

* store: no unverified receipts with a trusted key

* store: cap the log lines of refused webhooks

* store: check Apple certificates at the signed date

* store: refuse a malformed Stripe publishable key

* store: check the owner before a refund

* store: fold the names migrations into one

* store: read onion name links through the proxy

* store: refund money after paid once confirmed

* store: limit the allowance wait to a dry run

* store: bind loopback when upgrading

* ci: cache and widen the store Postgres job

* store: fix stale and duplicate names tests

* store: fix the submodule path in the upgrade

* store: refuse unpaid name codes on the CLI

* store: apply the review's names test list

* store: finish the review's names test list

* store: restore the base registration tests

* store: pass link hosts that do not resolve here

* store: refuse a move once its sends are used up

* store: take the shared checkout at the provider

* store: hold a search slot for chain reads only

* store: state which refunds are safe on a reference

* store: check a failed order's name before refusing its move (#8060)

* store: test and document the shared checkout cap for name orders

* store: check a failed order's name on chain before refusing its move

* store: test name links whose host lookup fails

* store: test that a search holds its slot through the chain reads only

* store: restore the signed transaction check in the chain tests

* store: remove the chain tests' copy of the signed transaction check

* store: correct the search slot texts and the README's balance endpoints

* docs: system and sequence diagrams of the names service (#8068)

---------

Co-authored-by: sh-agents <350651734+sh-agents@users.noreply.github.com>
Co-authored-by: Evgeny Poberezkin <evgeny@poberezkin.com>
Co-authored-by: brenzi-agent <brenzi-agent@brenzi.ch>
Co-authored-by: Evgeny @ SimpleX Chat <259188159+evgeny-simplex@users.noreply.github.com>
2026-11-07 10:45:19 +00:00

323 lines
18 KiB
Haskell
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TupleSections #-}
module Bots.StoreService.NamesCodesTests (namesCodesTests) where
import Bots.StoreService.NamesStoreTests (order, ownerA, ownerB, placeCode, placePaid, usable)
import Bots.StoreService.WebTests (withServiceStore, withApp)
import Control.Arrow ((&&&))
import Control.Concurrent (threadDelay)
import Control.Concurrent.Async (concurrently)
import Control.Monad (forM_)
import qualified Data.Aeson as J
import qualified Data.Aeson.KeyMap as KM
import qualified Data.ByteString.Lazy.Char8 as LB
import Data.IORef (newIORef, readIORef, writeIORef)
import Data.Maybe (fromJust, fromMaybe)
import Data.Text (Text)
import Data.Time.Calendar (fromGregorian)
import Data.Time.Clock (UTCTime (..), addUTCTime)
import Network.HTTP.Client (Manager, Response, RequestBody (..), httpLbs, method, parseRequest, requestBody, responseBody, responseStatus)
import Network.HTTP.Types.Status (statusCode)
import Simplex.Chat.Badges.Code (NameCode (..), NamePrepaidCode, formatNameCode, namePrepaidCodeHash, parseNameCode, randomNamePrepaidCode)
import Simplex.Chat.Badges.Types (BadgeCodePaymentStatus (..))
import Simplex.Chat.Types.Shared (GroupMemberRole (..))
import Simplex.Messaging.Agent.Store.Common (DBStore, withTransaction)
import qualified Simplex.Messaging.Agent.Store.DB as DB
import qualified Simplex.Messaging.Crypto as C
import StoreService.Config (ListenerConfig (..))
import StoreService.Group.Command (CmdAction (..), GroupCmd (..), groupCmdAction)
import StoreService.Names.Codes
import StoreService.Names.Phases (RegistrationId (..))
import StoreService.Names.Store (NewPrepaidCode (..), PrepaidCode (..), getPrepaidCode, insertPrepaidCode, reservePrepaidCode, revokePrepaidCode, spendLandedPrepaidCode)
import StoreService.Names.Turns (Turns, newTurns)
import StoreService.Store (RevokeResult (..))
import StoreService.Web.Http (codeLimit, newHttpEnv, notFound)
import StoreService.Web.Names (Route (..), namesApp)
import StoreService.Web.Names.Codes (codeCheckHandler)
import Test.Hspec
namesCodesTests :: Spec
namesCodesTests = describe "StoreService names: prepaid codes" $ do
describe "state" $
it "reads each state from the code's row, a spent code as used even if revoked while held" testCodeStates
describe "check" $ do
it "folds a code typed in lower case with spaces to the issued one, and changes no code" testCheckFolded
it "answers code_invalid to an unknown code, an owner code or other text" testCheckInvalid
it "answers bad_request to a body that is not an object with a code text" testCheckBadBody
describe "reservations" $ do
it "reserves an unused code after the registration's write, in its transaction" testReserve
it "refuses each unusable code with its tag, a code spent by the reserving registration itself as used, before the write runs" testReserveRefusals
it "keeps a code its registration holds even if revoked or expired since, still checking the length" testReserveHeld
it "reserves nothing when the write refuses" testReserveWriteRefused
it "rolls the write back when the code's reservation is refused after it" testReserveRollsBack
it "lets one of two concurrent reservations of a code win, the other answered code_reserved" testConcurrentReserve
it "releases and spends a code only after the write, and only for its holder" testReleaseSpend
describe "group commands" $ do
it "parses /issue name and /bulk name with the length, years and count" testGroupNameCommands
it "answers the usage to a bad length, years or count, or a badge option" testGroupNameCommandsRefused
it "parses /revoke of a prepaid code, telling a moderator it was not revoked" testGroupRevokeNameCommand
r1, r2 :: RegistrationId
r1 = RegistrationId "r1"
r2 = RegistrationId "r2"
tNow :: UTCTime
tNow = UTCTime (fromGregorian 2026 10 21) 3600
baseCode :: PrepaidCode
baseCode =
PrepaidCode
{ pcId = 1,
pcCodeHash = "",
pcMinLength = 8,
pcYears = 2,
pcPaymentStatus = CPSPaid,
pcReservedBy = Nothing,
pcReservedAt = Nothing,
pcSpentAt = Nothing,
pcRevokedAt = Nothing,
pcExpiresAt = Nothing,
pcCreatedAt = tNow
}
testCodeStates :: IO ()
testCodeStates = do
let stateOf = codeState tNow
held = baseCode {pcReservedBy = Just r1, pcReservedAt = Just tNow}
revoked = Just tNow
map codeStateText [minBound .. maxBound] `shouldBe` ["unused", "reserved", "used", "revoked", "expired", "unpaid"]
stateOf baseCode `shouldBe` CSUnused
stateOf baseCode {pcPaymentStatus = CPSFree, pcExpiresAt = Just (addUTCTime 1 tNow)} `shouldBe` CSUnused
stateOf held `shouldBe` CSReserved
stateOf held {pcSpentAt = Just tNow} `shouldBe` CSUsed
stateOf held {pcSpentAt = Just tNow, pcRevokedAt = revoked} `shouldBe` CSUsed
stateOf baseCode {pcRevokedAt = revoked} `shouldBe` CSRevoked
stateOf held {pcRevokedAt = revoked} `shouldBe` CSRevoked
stateOf baseCode {pcPaymentStatus = CPSUnpaid} `shouldBe` CSUnpaid
stateOf baseCode {pcPaymentStatus = CPSUnpaid, pcExpiresAt = Just tNow} `shouldBe` CSUnpaid
stateOf baseCode {pcExpiresAt = Just tNow} `shouldBe` CSExpired
stateOf held {pcExpiresAt = Just tNow} `shouldBe` CSReserved
-- The route as namesRoutes registers it, since a NamesEnv needs a running chat controller.
withCodeCheck :: (DBStore -> Client -> IO a) -> IO a
withCodeCheck action = withServiceStore $ \st -> do
http <- newHttpEnv ListenerConfig {lHost = "127.0.0.1", lBadgesPort = 0, lBadgesStaticDir = "", lServeWebapp = False, lBadgesExportDir = Nothing, lTrustForwardedFor = False, lNamesStaticDir = Nothing, lNamesExportDir = Nothing, lNamesPort = Nothing}
let routes = \case
["api", "code", "check"] -> Just Route {rMethod = "POST", rLimit = codeLimit, rHandler = codeCheckHandler st}
_ -> Nothing
app req respond = fromMaybe (respond notFound) (namesApp http routes req respond)
withApp app (action st)
type Client = (Manager, String)
postCheck :: Client -> LB.ByteString -> IO (Response LB.ByteString)
postCheck (mgr, base) body = do
req <- parseRequest (base <> "/api/code/check")
httpLbs req {method = "POST", requestBody = RequestBodyLBS body} mgr
checkText :: Client -> Text -> IO (Response LB.ByteString)
checkText client code = postCheck client (J.encode (J.object ["code" J..= code]))
checkCode :: Client -> NamePrepaidCode -> IO (Response LB.ByteString)
checkCode client = checkText client . formatNameCode . NCPrepaid
answerOf :: Response LB.ByteString -> (Int, Maybe J.Object)
answerOf r = (statusCode (responseStatus r), J.decode (responseBody r))
coverage :: Int -> Int -> Text -> (Int, Maybe J.Object)
coverage minLength years state = (200, Just $ KM.fromList [("minLength", J.toJSON minLength), ("years", J.toJSON years), ("state", J.String state)])
refused :: Int -> Text -> (Int, Maybe J.Object)
refused status tag = (status, Just $ KM.fromList [("error", J.String tag)])
newCode :: Int -> IO NamePrepaidCode
newCode len = C.newRandom >>= (`randomNamePrepaidCode` len)
issueAs :: DBStore -> NamePrepaidCode -> NewPrepaidCode -> IO PrepaidCode
issueAs st code new = withTransaction st $ \db -> do
Right _ <- insertPrepaidCode db new {npcCodeHash = namePrepaidCodeHash code} tNow
fromJust <$> getPrepaidCode db (namePrepaidCodeHash code)
readCode :: DBStore -> PrepaidCode -> IO (Maybe PrepaidCode)
readCode st PrepaidCode {pcCodeHash} = withTransaction st (`getPrepaidCode` pcCodeHash)
-- The webapp's and core's vector: these two spellings are one code.
testCheckFolded :: IO ()
testCheckFolded = withCodeCheck $ \st client -> do
Just (NCPrepaid code) <- pure $ parseNameCode "SN7-BJTBP-29596-R3HJ8-25YM7"
row <- issueAs st code usable {npcMinLength = 7}
unchanged <- readCode st row
answerOf <$> checkText client "sn7 bjtbp 29596 r3hj8 25ym7" `shouldReturn` coverage 7 2 "unused"
readCode st row `shouldReturn` unchanged
testCheckInvalid :: IO ()
testCheckInvalid = withCodeCheck $ \_ client -> do
unknown <- newCode 8
let invalid = refused 400 "code_invalid"
answerOf <$> checkCode client unknown `shouldReturn` invalid
forM_
[ "SN-DWPHS-6JBFR-ZR1MA-T5HQ9-P17QM-F5GM5",
"alicebakery"
]
$ \text -> (text,) . answerOf <$> checkText client text `shouldReturn` (text, invalid)
testCheckBadBody :: IO ()
testCheckBadBody = withCodeCheck $ \_ client -> do
let badRequest = refused 400 "bad_request"
forM_ ["", "not json", "[\"SN7-BJTBP-29596-R3HJ8-25YM7\"]", "{}", "{\"code\": 7}", "{\"code\": null}"] $ \body ->
(body,) . answerOf <$> postCheck client body `shouldReturn` (body, badRequest)
let overCap = "{\"code\": \"SN7-BJTBP-29596-R3HJ8-25YM7\", \"pad\": \"" <> LB.replicate 8192 'x' <> "\"}"
answerOf <$> postCheck client overCap `shouldReturn` badRequest
-- | Two paid orders, so a code can be reserved for either.
withOrders :: (Turns -> DBStore -> IO a) -> IO a
withOrders action = withServiceStore $ \st -> do
placePaid st "r1" ownerA (order "alicebakery" 1) tNow `shouldReturn` Right ()
placePaid st "r2" ownerB (order "bobsbakery" 2) tNow `shouldReturn` Right ()
turns <- newTurns
action turns st
writeOk :: DB.Connection -> IO (Either Text ())
writeOk _ = pure $ Right ()
testReserve :: IO ()
testReserve = withOrders $ \turns st -> do
code <- newCode 8
PrepaidCode {pcCodeHash} <- issueAs st code usable
let holderInWrite db = Right . (pcReservedBy =<<) <$> getPrepaidCode db pcCodeHash :: IO (Either Text (Maybe RegistrationId))
reserveCode turns st tNow pcCodeHash r1 8 holderInWrite `shouldReturn` Right (Right Nothing)
(pcReservedBy =<<) <$> withTransaction st (`getPrepaidCode` pcCodeHash) `shouldReturn` Just r1
reserveCode turns st tNow pcCodeHash r1 11 holderInWrite `shouldReturn` Right (Right (Just r1))
testReserveRefusals :: IO ()
testReserveRefusals = withOrders $ \turns st -> do
[reserved, used, own, revoked, expired, unpaid, unknown, short] <- mapM newCode [8, 8, 8, 8, 8, 8, 8, 8]
reservedRow <- issueAs st reserved usable
usedRow <- issueAs st used usable
ownRow <- issueAs st own usable
revokedRow <- issueAs st revoked usable
expiredRow <- issueAs st expired usable {npcExpiresAt = Just tNow}
unpaidRow <- issueAs st unpaid usable {npcPaymentStatus = CPSUnpaid}
shortRow <- issueAs st short usable
placeCode st "r5" ownerA (order "erinsbakery" 5) reservedRow `shouldReturn` Right ()
placeCode st "r3" ownerB (order "carolsbakery" 4) usedRow `shouldReturn` Right ()
withTransaction st (\db -> spendLandedPrepaidCode db (pcId usedRow) (RegistrationId "r3") tNow) `shouldReturn` True
placeCode st "r6" ownerB (order "franksbakery" 6) ownRow `shouldReturn` Right ()
withTransaction st (\db -> spendLandedPrepaidCode db (pcId ownRow) (RegistrationId "r6") tNow) `shouldReturn` True
withTransaction st (\db -> revokePrepaidCode db (pcCodeHash revokedRow) tNow) `shouldReturn` Revoked (pcId revokedRow)
wrote <- newIORef False
let reserveFor rid hash len = reserveCode turns st tNow hash rid len (\_ -> Right () <$ writeIORef wrote True :: IO (Either Text ()))
reserve = reserveFor r1
rows = [reservedRow, usedRow, ownRow, revokedRow, expiredRow, unpaidRow, shortRow]
rowsBefore <- mapM (readCode st) rows
reserve (pcCodeHash reservedRow) 8 `shouldReturn` Left CRReserved
reserve (pcCodeHash usedRow) 8 `shouldReturn` Left CRUsed
reserveFor (RegistrationId "r6") (pcCodeHash ownRow) 8 `shouldReturn` Left CRUsed
reserve (pcCodeHash revokedRow) 8 `shouldReturn` Left CRInvalid
reserve (pcCodeHash expiredRow) 8 `shouldReturn` Left CRExpired
reserve (pcCodeHash unpaidRow) 8 `shouldReturn` Left CRPaymentPending
reserve (namePrepaidCodeHash unknown) 8 `shouldReturn` Left CRInvalid
reserve (pcCodeHash shortRow) 7 `shouldReturn` Left CRNotCovering
reserve (pcCodeHash revokedRow) 7 `shouldReturn` Left CRInvalid
readIORef wrote `shouldReturn` False
mapM (readCode st) rows `shouldReturn` rowsBefore
map codeRefusalTag [CRInvalid, CRUsed, CRReserved, CRExpired, CRPaymentPending, CRNotCovering]
`shouldBe` ["code_invalid", "code_used", "code_reserved", "code_expired", "payment_pending", "code_not_covering"]
testReserveHeld :: IO ()
testReserveHeld = withOrders $ \turns st -> do
code <- newCode 8
row@PrepaidCode {pcCodeHash} <- issueAs st code usable
placeCode st "r3" ownerB (order "carolsbakery" 3) row `shouldReturn` Right ()
let r3 = RegistrationId "r3"
withTransaction st (\db -> revokePrepaidCode db pcCodeHash tNow) `shouldReturn` Revoked (pcId row)
withTransaction st $ \db -> DB.execute db "UPDATE sx_badge_service_name_prepaid_codes SET expires_at = ? WHERE code_hash = ?" (tNow, DB.Binary pcCodeHash)
held <- readCode st row
reserveCode turns st tNow pcCodeHash r3 9 writeOk `shouldReturn` Right (Right ())
reserveCode turns st tNow pcCodeHash r3 7 writeOk `shouldReturn` Left CRNotCovering
reserveCode turns st tNow pcCodeHash r1 9 writeOk `shouldReturn` Left CRInvalid
readCode st row `shouldReturn` held
testReserveWriteRefused :: IO ()
testReserveWriteRefused = withOrders $ \turns st -> do
code <- newCode 8
row@PrepaidCode {pcCodeHash} <- issueAs st code usable
reserveCode turns st tNow pcCodeHash r1 8 (\_ -> pure (Left "registration_changed" :: Either Text ())) `shouldReturn` Right (Left "registration_changed")
(pcReservedBy =<<) <$> readCode st row `shouldReturn` Nothing
reserveCode turns st tNow pcCodeHash r2 8 writeOk `shouldReturn` Right (Right ())
(pcReservedBy =<<) <$> readCode st row `shouldReturn` Just r2
-- | The write reserves the code for another registration, as a writer outside this process could between the check and the reservation.
testReserveRollsBack :: IO ()
testReserveRollsBack = withOrders $ \turns st -> do
code <- newCode 8
row@PrepaidCode {pcId, pcCodeHash} <- issueAs st code usable
let takenMeanwhile db = Right () <$ reservePrepaidCode db pcId r2 tNow :: IO (Either Text ())
reserveCode turns st tNow pcCodeHash r1 8 takenMeanwhile `shouldReturn` Left CRReserved
readCode st row `shouldReturn` Just row
testConcurrentReserve :: IO ()
testConcurrentReserve = withOrders $ \turns st -> do
code <- newCode 8
row@PrepaidCode {pcCodeHash} <- issueAs st code usable
let slowWrite _ = Right () <$ threadDelay 100000 :: IO (Either Text ())
reserveFor rid = reserveCode turns st tNow pcCodeHash rid 8 slowWrite
outcomes <- concurrently (reserveFor r1) (reserveFor r2)
outcomes `shouldSatisfy` (`elem` [(Right (Right ()), Left CRReserved), (Left CRReserved, Right (Right ()))])
holder <- (pcReservedBy =<<) <$> readCode st row
holder `shouldBe` Just (if fst outcomes == Right (Right ()) then r1 else r2)
testReleaseSpend :: IO ()
testReleaseSpend = withOrders $ \turns st -> do
[spent, released] <- mapM newCode [8, 8]
spentRow <- issueAs st spent usable
releasedRow <- issueAs st released usable
placeCode st "r3" ownerB (order "carolsbakery" 3) spentRow `shouldReturn` Right ()
placeCode st "r4" ownerB (order "davesbakery" 4) releasedRow `shouldReturn` Right ()
let r3 = RegistrationId "r3"
r4 = RegistrationId "r4"
holderInWrite row db = Right . (pcReservedBy =<<) <$> getPrepaidCode db (pcCodeHash row) :: IO (Either Text (Maybe RegistrationId))
changed _ = pure (Left "registration_changed") :: IO (Either Text ())
spendLandedCode turns st tNow (pcId spentRow) r3 changed `shouldReturn` Left "registration_changed"
(pcSpentAt =<<) <$> readCode st spentRow `shouldReturn` Nothing
spendLandedCode turns st tNow (pcId spentRow) r1 writeOk `shouldReturn` Right ((), False)
spendLandedCode turns st tNow (pcId spentRow) r3 writeOk `shouldReturn` Right ((), True)
((pcReservedBy =<<) &&& (pcSpentAt =<<)) <$> readCode st spentRow `shouldReturn` (Just r3, Just tNow)
releaseCode turns st (pcId spentRow) r3 writeOk `shouldReturn` Right ((), False)
releaseCode turns st (pcId releasedRow) r4 changed `shouldReturn` Left "registration_changed"
releaseCode turns st (pcId releasedRow) r1 writeOk `shouldReturn` Right ((), False)
releaseCode turns st (pcId releasedRow) r4 (holderInWrite releasedRow) `shouldReturn` Right (Just r4, True)
(pcReservedBy =<<) <$> readCode st releasedRow `shouldReturn` Nothing
testGroupNameCommands :: IO ()
testGroupNameCommands = do
let p = groupCmdAction GRAdmin
p "/issue name 8" `shouldBe` RunCmd (GCIssueName 8 2)
p "/issue name 6 years 5" `shouldBe` RunCmd (GCIssueName 6 5)
p "/issue name 63 years 10" `shouldBe` RunCmd (GCIssueName 63 10)
p "/bulk name 7 count 3" `shouldBe` RunCmd (GCBulkName 7 2 3)
p "/bulk name 12 years 3 count 100" `shouldBe` RunCmd (GCBulkName 12 3 100)
p "/bulk name 6 count 100" `shouldBe` RunCmd (GCBulkName 6 2 100)
groupCmdAction GRMember "/issue name 8" `shouldBe` IgnoreMsg
testGroupRevokeNameCommand :: IO ()
testGroupRevokeNameCommand = do
code <- newCode 8
let cmd = "/revoke " <> formatNameCode (NCPrepaid code)
groupCmdAction GRAdmin cmd `shouldBe` RunCmd (GCRevokeName code)
groupCmdAction GRModerator cmd `shouldBe` ReplyText "Only admins can revoke codes. This code is now visible to all members."
groupCmdAction GRAdmin (cmd <> " junk") `shouldBe` ReplyText "Usage: /revoke <code>"
testGroupNameCommandsRefused :: IO ()
testGroupNameCommandsRefused = do
let p = groupCmdAction GRModerator
issueUsage = ReplyText "Usage: /issue <kind> [<length>] [years <Y> | months <M>] [uses <N>]\nname <length>: length 6–63, years 2–10\nsupporter, legend, investor: months 1–255, uses 1–1000\ne.g. /issue name 6 years 5 · /issue supporter months 12"
bulkUsage = ReplyText "Usage: /bulk <kind> [<length>] [years <Y> | months <M>] count <N>\nname <length>: length 6–63, years 2–10, count 1–100\nsupporter, legend, investor: months 1–255, count 1–100\ne.g. /bulk name 6 count 100 · /bulk legend months 3 count 10"
forM_ ["name", "name 5", "name 64", "name 06", "name 8 years 1", "name 8 years 0", "name 8 years 11", "name 8 uses 2", "name 8 months 2", "name 8 paid", "name 8 years 18446744073709551618", "name 8 count 2", "name 8 count 1"] $ \args ->
(args, p ("/issue " <> args)) `shouldBe` (args, issueUsage)
forM_ ["name 8", "name 8 count 0", "name 8 count 101", "name 8 years 1 count 2", "name 5 count 2", "name 08 count 2", "name 8 months 2 count 2", "name 8 count 2 uses 2", "name 8 uses 2 count 2", "name 8 count 2 years 5", "name count 2"] $ \args ->
(args, p ("/bulk " <> args)) `shouldBe` (args, bulkUsage)