streamlit

Форк
0
/
delta_generator_test_case.py 
94 строки · 3.7 Кб
1
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2024)
2
#
3
# Licensed under the Apache License, Version 2.0 (the "License");
4
# you may not use this file except in compliance with the License.
5
# You may obtain a copy of the License at
6
#
7
#     http://www.apache.org/licenses/LICENSE-2.0
8
#
9
# Unless required by applicable law or agreed to in writing, software
10
# distributed under the License is distributed on an "AS IS" BASIS,
11
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
# See the License for the specific language governing permissions and
13
# limitations under the License.
14

15
"""Base class for DeltaGenerator-related unit tests."""
16

17
import threading
18
import unittest
19
from typing import List
20
from unittest.mock import MagicMock
21

22
from streamlit.proto.Delta_pb2 import Delta
23
from streamlit.proto.ForwardMsg_pb2 import ForwardMsg
24
from streamlit.runtime import Runtime
25
from streamlit.runtime.caching.storage.dummy_cache_storage import (
26
    MemoryCacheStorageManager,
27
)
28
from streamlit.runtime.forward_msg_queue import ForwardMsgQueue
29
from streamlit.runtime.media_file_manager import MediaFileManager
30
from streamlit.runtime.memory_media_file_storage import MemoryMediaFileStorage
31
from streamlit.runtime.memory_uploaded_file_manager import MemoryUploadedFileManager
32
from streamlit.runtime.scriptrunner import (
33
    ScriptRunContext,
34
    add_script_run_ctx,
35
    get_script_run_ctx,
36
)
37
from streamlit.runtime.scriptrunner.script_requests import ScriptRequests
38
from streamlit.runtime.state import SafeSessionState, SessionState
39
from streamlit.web.server.server import MEDIA_ENDPOINT, UPLOAD_FILE_ENDPOINT
40

41

42
class DeltaGeneratorTestCase(unittest.TestCase):
43
    def setUp(self):
44
        self.forward_msg_queue = ForwardMsgQueue()
45

46
        # Save our thread's current ScriptRunContext
47
        self.orig_report_ctx = get_script_run_ctx()
48

49
        # Create a new ScriptRunContext to use for the test.
50
        self.script_run_ctx = ScriptRunContext(
51
            session_id="test session id",
52
            _enqueue=self.forward_msg_queue.enqueue,
53
            query_string="",
54
            session_state=SafeSessionState(SessionState(), lambda: None),
55
            uploaded_file_mgr=MemoryUploadedFileManager(UPLOAD_FILE_ENDPOINT),
56
            main_script_path="",
57
            page_script_hash="",
58
            user_info={"email": "test@test.com"},
59
            script_requests=ScriptRequests(),
60
        )
61
        add_script_run_ctx(threading.current_thread(), self.script_run_ctx)
62

63
        # Create a MemoryMediaFileStorage instance, and the MediaFileManager
64
        # singleton.
65
        self.media_file_storage = MemoryMediaFileStorage(MEDIA_ENDPOINT)
66

67
        mock_runtime = MagicMock(spec=Runtime)
68
        mock_runtime.cache_storage_manager = MemoryCacheStorageManager()
69
        mock_runtime.media_file_mgr = MediaFileManager(self.media_file_storage)
70
        mock_runtime.uploaded_file_mgr = self.script_run_ctx.uploaded_file_mgr
71
        Runtime._instance = mock_runtime
72

73
    def tearDown(self):
74
        self.clear_queue()
75
        add_script_run_ctx(threading.current_thread(), self.orig_report_ctx)
76
        Runtime._instance = None
77

78
    def get_message_from_queue(self, index=-1) -> ForwardMsg:
79
        """Get a ForwardMsg proto from the queue, by index."""
80
        return self.forward_msg_queue._queue[index]
81

82
    def get_delta_from_queue(self, index=-1) -> Delta:
83
        """Get a Delta proto from the queue, by index."""
84
        deltas = self.get_all_deltas_from_queue()
85
        return deltas[index]
86

87
    def get_all_deltas_from_queue(self) -> List[Delta]:
88
        """Return all the delta messages in our ForwardMsgQueue"""
89
        return [
90
            msg.delta for msg in self.forward_msg_queue._queue if msg.HasField("delta")
91
        ]
92

93
    def clear_queue(self) -> None:
94
        self.forward_msg_queue.clear()
95

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.