tests: cover the handlers that stop cancelled actions (#8301)

* tests: stop cancelled actions instead of continuing them

* tests: share the resource holder of the time limit tests

* tests: limit the wait for a held resource and report its failure
This commit is contained in:
Evgeny @ SimpleX Chat authored and GitHub committed 2026-11-21 23:40:38 +00:00
1 parent c2d66c9d1d
commit ddcdc1b504
6 files changed
+79 -5

No files matched your search

+1 -1
View File
@@ -4,7 +4,7 @@
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Simplex.Chat.Terminal.Notification (Notification (..), initializeNotifications) where
module Simplex.Chat.Terminal.Notification (Notification (..), hideException, initializeNotifications) where
import Data.List (isInfixOf)
import Data.Maybe (isJust)
+20
View File
@@ -34,6 +34,7 @@ import Simplex.Chat.Controller (ChatConfig (..), ChatController (..), ChatEvent
import Simplex.Chat.Messages (AChatItemUpdate (..), CIMeta (CIMeta, itemText), ChatItem (ChatItem, meta), ChatItemId)
import Simplex.Chat.Options
import Simplex.Chat.Protocol (supportedChatVRange)
import Simplex.Chat.Terminal.Notification (hideException)
import Simplex.Chat.Types (ContactId, VersionRangeChat, authErrDisableCount, sameVerificationCode, verificationCode, pattern VersionChat)
import Simplex.Messaging.Agent.Env.SQLite
import Simplex.Messaging.Agent.RetryInterval
@@ -49,12 +50,16 @@ import Simplex.Messaging.Version
import System.Directory (copyFile, doesDirectoryExist, doesFileExist)
import System.Mem.Weak (deRefWeak)
import System.FilePath ((</>))
import System.Timeout (timeout)
import Test.Hspec hiding (it)
#if defined(dbPostgres)
import Database.PostgreSQL.Simple (Only (..))
#else
import Database.SQLite.Simple (Only (..))
import Simplex.Chat.Options.DB
import Simplex.Chat.Terminal.Input (updateTermState)
import Simplex.Chat.Terminal.Output (TerminalState (inputString), mkTermState)
import System.Terminal (Key (TabKey))
#endif
chatDirectTests :: SpecWith TestParams
@@ -149,6 +154,12 @@ chatDirectTests = do
describe "settings" $ do
it "set chat item expiration TTL" testSetChatItemTTL
it "save/get app settings" testAppSettings
describe "terminal" $ do
it "should stop a notification at its time limit" $ \_ ->
timeout 100000 (hideException (\_ -> threadDelay 1000000) ()) `shouldReturn` Nothing
#if !defined(dbPostgres)
it "should stop a name completion at its time limit" testNameCompletionTimeLimit
#endif
describe "connection switch" $ do
it "switch contact to a different queue" testSwitchContact
it "stop switching contact to a different queue" testAbortSwitchContact
@@ -3086,6 +3097,15 @@ testAppSettings ps =
alice ##> "/_get app settings"
alice <## ("app settings: " <> settingsApp)
#if !defined(dbPostgres)
testNameCompletionTimeLimit :: HasCallStack => TestParams -> IO ()
testNameCompletionTimeLimit ps =
withNewTestChat ps "alice" aliceProfile $ \alice@TestCC {chatController = ChatController {chatStore}} ->
withCCUser alice $ \user -> do
let complete = updateTermState (Just user) chatStore "" False 80 (TabKey, mempty) mkTermState {inputString = "@a"}
holdDuring (withCCTransaction alice . const) (timeout 100000 $ void complete) `shouldReturn` Nothing
#endif
testSwitchContact :: HasCallStack => TestParams -> IO ()
testSwitchContact =
testChat2 aliceProfile bobProfile $
+14 -2
View File
@@ -23,11 +23,12 @@ import Data.Int (Int64)
import qualified Data.Text as T
import Network.HTTP.Types.URI (urlEncode)
import Data.Time.Clock (addUTCTime, getCurrentTime, nominalDay)
import GHC.IO.Handle.Internals (withHandle_)
import Simplex.Chat.Badges (BadgeProof, BadgeStatus (..), BadgeType (..), FileSizeLimits (..), ProofPresHeader (..), badgeProof, defaultFileSizeLimits)
import Simplex.Chat.Controller (ChatCommand (APIGetChat), ChatConfig (..), ChatEvent (CEvtChatItemUpdated, CEvtRcvFileDescrReady), ChatHooks (..), ChatPagination (CPLast), ChatResponse (CRApiChat, CRNewChatItems), defaultChatHooks)
import Simplex.Chat.Controller (ChatCommand (APIGetChat), ChatConfig (..), ChatController (rcvFiles), ChatEvent (CEvtChatItemUpdated, CEvtRcvFileDescrReady), ChatHooks (..), ChatPagination (CPLast), ChatResponse (CRApiChat, CRNewChatItems), defaultChatHooks)
import Simplex.Chat.Core (sendChatCmdStr)
import Simplex.Chat.Library.Commands (execChatCommand')
import Simplex.Chat.Library.Internal (badgeProofStatus, roundedFDCount)
import Simplex.Chat.Library.Internal (badgeProofStatus, closeFileHandle, getFileHandle, roundedFDCount)
import Simplex.Chat.Markdown (parseMaybeMarkdownList)
import Simplex.Chat.Messages (AChat (..), AChatItem (..), AChatItemUpdate (..), CChatItem (..), CIFile (..), CIQuote (CIQuote, content, formattedText), Chat (..), ChatItem (..), ChatRef (..), ChatType (..))
import Simplex.Chat.Messages.CIContent (MsgDirectionI, ciMsgContent)
@@ -43,6 +44,7 @@ import Simplex.Messaging.Crypto.File (CryptoFile (..), CryptoFileArgs (..))
import Simplex.Messaging.Encoding.String
import System.Directory (copyFile, createDirectoryIfMissing, doesFileExist, getFileSize)
import System.FilePath ((</>))
import System.IO (IOMode (..), hClose)
import System.Timeout (timeout)
import Test.Hspec hiding (it)
@@ -108,6 +110,8 @@ chatFileTests = do
it "sending file above the limit the badge allows fails" testXFTPSndFileBadgeLimit
it "sending file with a badge expired past the send grace fails" testXFTPSndFileBadgeGrace
it "file proof is rejected under another binding, size or expired badge" testFileBadgeProofStatus
describe "file handles" $ do
it "should stop closing a file at its time limit" testCloseFileTimeLimit
runTestMessageWithFile :: HasCallStack => TestParams -> IO ()
runTestMessageWithFile = testChat2 aliceProfile bobProfile $ \alice bob -> withXFTPServer alice $ do
@@ -1747,3 +1751,11 @@ testXFTPStandaloneCancelRcv = testChat2 aliceProfile aliceDesktopProfile $ \src
dst <## "cancelled receiving file 1 (testfile.out)"
threadDelay 25000
doesFileExist dstFile `shouldReturn` False
testCloseFileTimeLimit :: HasCallStack => TestParams -> IO ()
testCloseFileTimeLimit ps =
withNewTestChat ps "alice" aliceProfile $ \TestCC {chatController = cc} -> do
Right h <- runReaderT (runExceptT $ getFileHandle 1 (tmpFile ps "test.txt") rcvFiles AppendMode) cc
r <- holdDuring (withHandle_ "testCloseFileTimeLimit" h . const) (timeout 100000 $ runReaderT (closeFileHandle 1 rcvFiles) cc)
hClose h
r `shouldBe` Nothing
+22
View File
@@ -65,8 +65,13 @@ import Test.Hspec hiding (it)
#if defined(dbPostgres)
import Control.Concurrent (newEmptyMVar, putMVar, takeMVar)
import Control.Concurrent.Async (wait, withAsync)
import Data.List.NonEmpty (NonEmpty (..))
import Data.Maybe (isNothing)
import Database.PostgreSQL.Simple (Only (..))
import Database.PostgreSQL.Simple.SqlQQ (sql)
import Simplex.Chat.Library.Subscriber (processAgentMessage)
import Simplex.Messaging.Agent.Protocol (AEvent (MERRS), AgentErrorType (INTERNAL))
import System.Timeout (timeout)
#else
import Database.SQLite.Simple (Only (..))
import Database.SQLite.Simple.QQ (sql)
@@ -116,6 +121,9 @@ chatGroupTests = do
it "remove member with messages mark deleted" testDeleteMemberMarkMessagesDeleted
it "remove member - delete messages of left/removed members" testDeleteMemberMessagesLeftRemoved
it "file chunks from a member who did not send the file are ignored" testGroupFileChunkOtherMember
#if defined(dbPostgres)
it "should stop a message error update at its time limit" testGroupMsgErrorsTimeLimit
#endif
describe "batch send messages" $ do
it "send multiple messages api" testSendMulti
it "send multiple timed messages" testSendMultiTimed
@@ -2302,6 +2310,20 @@ testGroupFileChunkOtherMember =
src <- B.readFile "./tests/fixtures/test.txt"
B.readFile (tmpFile bob "test.txt") `shouldReturn` src
#if defined(dbPostgres)
testGroupMsgErrorsTimeLimit :: HasCallStack => TestParams -> IO ()
testGroupMsgErrorsTimeLimit =
testChat2 aliceProfile bobProfile $
\alice@TestCC {chatController = cc} bob -> do
createGroup2 "team" alice bob
connId <- relayConnIdToMember alice "bob"
alice ##> "/_stop"
alice <## "chat stopped"
let lockDeliveries inside = withCCTransaction alice $ \db -> DB.execute_ db "LOCK TABLE msg_deliveries" >> inside
r <- holdDuring lockDeliveries (timeout 1000000 $ runReaderT (runExceptT $ processAgentMessage "" connId $ MERRS (1 :| []) (INTERNAL "")) cc)
r `shouldSatisfy` isNothing
#endif
testSendMulti :: HasCallStack => TestParams -> IO ()
testSendMulti =
testChat3 aliceProfile bobProfile cathProfile $
+10 -2
View File
@@ -11,8 +11,8 @@ module ChatTests.Utils where
import APIDocs (testGenerate)
import ChatClient
import ChatTests.DBUtils
import Control.Concurrent (threadDelay)
import Control.Concurrent.Async (concurrently_, mapConcurrently_)
import Control.Concurrent (newEmptyMVar, putMVar, takeMVar, threadDelay)
import Control.Concurrent.Async (concurrently_, mapConcurrently_, race_, wait, withAsync)
import Control.Concurrent.STM
import Control.Monad (join, unless, when)
import Control.Monad.Except (runExceptT)
@@ -674,6 +674,14 @@ withCCAgentTransaction :: TestCC -> (DB.Connection -> IO a) -> IO a
withCCAgentTransaction TestCC {chatController = ChatController {smpAgent}} action =
withTransaction (agentClientStore smpAgent) $ \db -> action db
holdDuring :: (IO () -> IO ()) -> IO a -> IO a
holdDuring hold action = do
held <- newEmptyMVar
release <- newEmptyMVar
withAsync (hold $ putMVar held () >> takeMVar release) $ \holder -> do
timeout 30000000 (race_ (takeMVar held) (wait holder)) `shouldReturn` Just ()
action <* (putMVar release () >> wait holder)
checkPendingInvitations :: HasCallStack => TestCC -> Int -> IO ()
checkPendingInvitations cc n =
withCCAgentTransaction cc (\db -> DB.query_ db "SELECT count(1) FROM conn_invitations WHERE accepted = 0") `shouldReturn` [[n]]
+12
View File
@@ -7,6 +7,7 @@ import Codec.Picture.JPEGTurbo (encodeRGB)
import Codec.Picture.Jpg (encodeDirectJpegAtQualityWithMetadata, encodeJpegAtQuality)
import Codec.Picture.Png (encodePng)
import Codec.Picture.Types (convertImage, extractLumaPlane, pixelFold)
import Control.Exception (bracket)
import Control.Monad (forM_, when)
import Control.Monad.Except (runExceptT)
import Data.Bits (complement, shiftR, testBit, xor)
@@ -23,6 +24,9 @@ import qualified Simplex.Messaging.Crypto as C
import Simplex.Messaging.Crypto.File (CryptoFile (..))
import qualified Simplex.Messaging.Crypto.File as CF
import System.FilePath ((</>))
import System.IO (IOMode (..), hClose, openFile)
import System.Process (callProcess)
import System.Timeout (timeout)
import Test.Hspec
import UnliftIO.STM (atomically)
import UnliftIO.Temporary (withTempDirectory)
@@ -47,6 +51,7 @@ imageTests = do
it "should generate preview of an encrypted image file" testEncryptedFilePreview
it "should keep the fixed preview when the file is not an image" $
imagePreview (CryptoFile "tests/fixtures/test.pdf" Nothing) `shouldReturn` fixedImagePreview
it "should stop an image preview at its time limit" testImagePreviewTimeLimit
describe "JPEG decoding" $ do
it "should decode JPEG at the display size" testJpegDisplaySize
it "should decode JPEG colour spaces" testJpegColourSpaces
@@ -170,6 +175,13 @@ testEncryptedFilePreview = withTempDirectory "tests/tmp" "image-preview" $ \dir
Right () <- runExceptT . CF.writeFile f . LB.fromStrict =<< B.readFile "tests/fixtures/test.jpg"
testFilePreview f
testImagePreviewTimeLimit :: IO ()
testImagePreviewTimeLimit = withTempDirectory "tests/tmp" "image-preview" $ \dir -> do
let path = dir </> "test.jpg"
callProcess "mkfifo" [path]
bracket (openFile path ReadWriteMode) hClose $ \_ ->
timeout 100000 (imagePreview $ CryptoFile path Nothing) `shouldReturn` Nothing
testJpegDisplaySize :: IO ()
testJpegDisplaySize =
forM_ sizes $ \(w, (w', h')) ->