Skip to content

SyncTestCase

Sync test classes.

SyncTestCase

Bases: BaseTestCase[Literal[False]]

Synchronous testing case.

Example

from qtasks import QueueTasks
from qtasks.tests import SyncTestCase

app = QueueTasks()

test_case = SyncTestCase(app=app)
Source code in src/qtasks/tests/sync_testcase.py
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
class SyncTestCase(BaseTestCase[Literal[False]]):
    """
    Synchronous testing case.

    ## Example

    ```python
    from qtasks import QueueTasks
    from qtasks.tests import SyncTestCase

    app = QueueTasks()

    test_case = SyncTestCase(app=app)
    ```
    """

    def __init__(
        self,
        app: Annotated[
            "QueueTasks",
            Doc("""
                    Main copy.
                    """),
        ],
        name: Annotated[
            str | None,
            Doc("""
                    Project name. This name can be used for test components.

                    Default: `None`.
                    """),
        ] = None,
    ):
        """
        Synchronous test case.

        Args:
            app(QueueTasks): Main instance.
            name (str, optional): Project name. This name can be used for test components. Default: `None`.
        """
        super().__init__(app=app, name=name)
        self.app: QueueTasks

    def start_in_background(
        self,
        starter: Annotated[
            Optional["BaseStarter"],
            Doc("""
                    Starter. Stores methods for launching components.

                    Default: `qtasks.starters.AsyncStarter`.
                    """),
        ] = None,
        num_workers: Annotated[
            int,
            Doc("""
                    Number of running workers.

                    Default: `4`.
                    """),
        ] = 4,
        reset_config: Annotated[
            bool,
            Doc("""
                    Update the config of the worker and broker.

                    Default: `True`.
                    """),
        ] = True,
    ):
        """
        Run `app.run_forever()` in the background.

        Args:
            starter (BaseStarter, optional): Starter. Default: `qtasks.starters.AsyncStarter`.
            num_workers (int, optional): Number of workers running. Default: 4.
            reset_config (bool, optional): Update the config of the worker and broker. Default: True.
        """

        def run():
            self.start(
                starter=starter, num_workers=num_workers, reset_config=reset_config
            )

        thread = threading.Thread(target=run, daemon=True)
        thread.start()

    def start(
        self,
        starter: Annotated[
            Optional["BaseStarter"],
            Doc("""
                    Starter. Stores methods for launching components.

                    Default: `qtasks.starters.AsyncStarter`.
                    """),
        ] = None,
        num_workers: Annotated[
            int,
            Doc("""
                    Number of running workers.

                    Default: `4`.
                    """),
        ] = 4,
        reset_config: Annotated[
            bool,
            Doc("""
                    Update the config of the worker and broker.

                    Default: `True`.
                    """),
        ] = True,
    ) -> None:
        """
        Runs `app.run_forever()`.

        Args:
            starter (BaseStarter, optional): Starter. Default: `qtasks.starters.AsyncStarter`.
            num_workers (int, optional): Number of workers running. Default: 4.
            reset_config (bool, optional): Update the config of the worker and broker. Default: True.
        """
        self.app.run_forever(
            starter=starter, num_workers=num_workers, reset_config=reset_config
        )

    def stop(self):
        """Stops the test case."""
        if self.test_config.global_config and self.app.broker.storage.global_config:
            self.app.broker.storage.global_config.stop()

        if self.test_config.storage:
            self.app.broker.storage.stop()

        if self.test_config.broker:
            self.app.broker.stop()

        if self.test_config.worker:
            self.app.worker.stop()

    def add_task(
        self,
        task_name: Annotated[
            str,
            Doc("""
                    Task name.
                    """),
        ],
        *args: Annotated[
            Any,
            Doc("""
                    args of the task.

                    Default: `()`.
                    """),
        ],
        priority: Annotated[
            int,
            Doc("""
                    The task has priority.

                    Default: `0`.
                    """),
        ] = 0,
        timeout: Annotated[
            float | None,
            Doc("""
                    Task timeout.

                    If specified, the task is returned via `qtasks.results.AsyncTask`.
                    """),
        ] = None,
        **kwargs: Annotated[
            Any,
            Doc("""
                    kwargs tasks.

                    Default: `{}`.
                    """),
        ],
    ) -> Union["Task", None]:
        """
        Add a task.

        Args:
            task_name (str): The name of the task.
            priority (int, optional): Task priority. Default: `0`.
            args (tuple, optional): task args. Default: `()`.
            kwargs (dict, optional): kwargs of tasks. Default: `{}`
            timeout (float, optional): Task timeout. If specified, the task is called via `qtasks.results.SyncResult`.

        Returns:
            Task|None: Task data or None.
        """
        if self.test_config.broker:
            return self.app.add_task(
                task_name, *args, priority=priority, timeout=timeout, **kwargs
            )
        elif self.test_config.worker:
            return self.app.worker.add(
                name=task_name,
                uuid=uuid4(),
                priority=priority,
                created_at=time(),
                args=args,
                kwargs=kwargs,
            )
        else:
            print(
                f"[SyncTestCase: {self.name}] Be sure to enable Worker or Broker!"
            )
            return

    def get(
        self,
        uuid: Annotated[
            UUID | str,
            Doc("""
                    UUID of the task.
                    """),
        ],
    ) -> Union["Task", None]:
        """
        Get a task.

        Args:
            uuid (UUID|str): UUID of the Task.

        Returns:
            Task|None: Task data or None.
        """
        if isinstance(uuid, str):
            uuid = UUID(uuid)
        if not self.test_config.broker:
            print(f"[SyncTestCase: {self.name}] Broker is not started!")
            return
        return self.app.broker.get(uuid=uuid)

__init__(app, name=None)

Synchronous test case.

Parameters:

Name Type Description Default
app QueueTasks

Main instance.

required
name str

Project name. This name can be used for test components. Default: None.

None
Source code in src/qtasks/tests/sync_testcase.py
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
def __init__(
    self,
    app: Annotated[
        "QueueTasks",
        Doc("""
                Main copy.
                """),
    ],
    name: Annotated[
        str | None,
        Doc("""
                Project name. This name can be used for test components.

                Default: `None`.
                """),
    ] = None,
):
    """
    Synchronous test case.

    Args:
        app(QueueTasks): Main instance.
        name (str, optional): Project name. This name can be used for test components. Default: `None`.
    """
    super().__init__(app=app, name=name)
    self.app: QueueTasks

add_task(task_name, *args, priority=0, timeout=None, **kwargs)

Add a task.

Parameters:

Name Type Description Default
task_name str

The name of the task.

required
priority int

Task priority. Default: 0.

0
args tuple

task args. Default: ().

()
kwargs dict

kwargs of tasks. Default: {}

{}
timeout float

Task timeout. If specified, the task is called via qtasks.results.SyncResult.

None

Returns:

Type Description
Union[Task, None]

Task|None: Task data or None.

Source code in src/qtasks/tests/sync_testcase.py
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
def add_task(
    self,
    task_name: Annotated[
        str,
        Doc("""
                Task name.
                """),
    ],
    *args: Annotated[
        Any,
        Doc("""
                args of the task.

                Default: `()`.
                """),
    ],
    priority: Annotated[
        int,
        Doc("""
                The task has priority.

                Default: `0`.
                """),
    ] = 0,
    timeout: Annotated[
        float | None,
        Doc("""
                Task timeout.

                If specified, the task is returned via `qtasks.results.AsyncTask`.
                """),
    ] = None,
    **kwargs: Annotated[
        Any,
        Doc("""
                kwargs tasks.

                Default: `{}`.
                """),
    ],
) -> Union["Task", None]:
    """
    Add a task.

    Args:
        task_name (str): The name of the task.
        priority (int, optional): Task priority. Default: `0`.
        args (tuple, optional): task args. Default: `()`.
        kwargs (dict, optional): kwargs of tasks. Default: `{}`
        timeout (float, optional): Task timeout. If specified, the task is called via `qtasks.results.SyncResult`.

    Returns:
        Task|None: Task data or None.
    """
    if self.test_config.broker:
        return self.app.add_task(
            task_name, *args, priority=priority, timeout=timeout, **kwargs
        )
    elif self.test_config.worker:
        return self.app.worker.add(
            name=task_name,
            uuid=uuid4(),
            priority=priority,
            created_at=time(),
            args=args,
            kwargs=kwargs,
        )
    else:
        print(
            f"[SyncTestCase: {self.name}] Be sure to enable Worker or Broker!"
        )
        return

get(uuid)

Get a task.

Parameters:

Name Type Description Default
uuid UUID | str

UUID of the Task.

required

Returns:

Type Description
Union[Task, None]

Task|None: Task data or None.

Source code in src/qtasks/tests/sync_testcase.py
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
def get(
    self,
    uuid: Annotated[
        UUID | str,
        Doc("""
                UUID of the task.
                """),
    ],
) -> Union["Task", None]:
    """
    Get a task.

    Args:
        uuid (UUID|str): UUID of the Task.

    Returns:
        Task|None: Task data or None.
    """
    if isinstance(uuid, str):
        uuid = UUID(uuid)
    if not self.test_config.broker:
        print(f"[SyncTestCase: {self.name}] Broker is not started!")
        return
    return self.app.broker.get(uuid=uuid)

start(starter=None, num_workers=4, reset_config=True)

Runs app.run_forever().

Parameters:

Name Type Description Default
starter BaseStarter

Starter. Default: qtasks.starters.AsyncStarter.

None
num_workers int

Number of workers running. Default: 4.

4
reset_config bool

Update the config of the worker and broker. Default: True.

True
Source code in src/qtasks/tests/sync_testcase.py
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
def start(
    self,
    starter: Annotated[
        Optional["BaseStarter"],
        Doc("""
                Starter. Stores methods for launching components.

                Default: `qtasks.starters.AsyncStarter`.
                """),
    ] = None,
    num_workers: Annotated[
        int,
        Doc("""
                Number of running workers.

                Default: `4`.
                """),
    ] = 4,
    reset_config: Annotated[
        bool,
        Doc("""
                Update the config of the worker and broker.

                Default: `True`.
                """),
    ] = True,
) -> None:
    """
    Runs `app.run_forever()`.

    Args:
        starter (BaseStarter, optional): Starter. Default: `qtasks.starters.AsyncStarter`.
        num_workers (int, optional): Number of workers running. Default: 4.
        reset_config (bool, optional): Update the config of the worker and broker. Default: True.
    """
    self.app.run_forever(
        starter=starter, num_workers=num_workers, reset_config=reset_config
    )

start_in_background(starter=None, num_workers=4, reset_config=True)

Run app.run_forever() in the background.

Parameters:

Name Type Description Default
starter BaseStarter

Starter. Default: qtasks.starters.AsyncStarter.

None
num_workers int

Number of workers running. Default: 4.

4
reset_config bool

Update the config of the worker and broker. Default: True.

True
Source code in src/qtasks/tests/sync_testcase.py
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
def start_in_background(
    self,
    starter: Annotated[
        Optional["BaseStarter"],
        Doc("""
                Starter. Stores methods for launching components.

                Default: `qtasks.starters.AsyncStarter`.
                """),
    ] = None,
    num_workers: Annotated[
        int,
        Doc("""
                Number of running workers.

                Default: `4`.
                """),
    ] = 4,
    reset_config: Annotated[
        bool,
        Doc("""
                Update the config of the worker and broker.

                Default: `True`.
                """),
    ] = True,
):
    """
    Run `app.run_forever()` in the background.

    Args:
        starter (BaseStarter, optional): Starter. Default: `qtasks.starters.AsyncStarter`.
        num_workers (int, optional): Number of workers running. Default: 4.
        reset_config (bool, optional): Update the config of the worker and broker. Default: True.
    """

    def run():
        self.start(
            starter=starter, num_workers=num_workers, reset_config=reset_config
        )

    thread = threading.Thread(target=run, daemon=True)
    thread.start()

stop()

Stops the test case.

Source code in src/qtasks/tests/sync_testcase.py
144
145
146
147
148
149
150
151
152
153
154
155
156
def stop(self):
    """Stops the test case."""
    if self.test_config.global_config and self.app.broker.storage.global_config:
        self.app.broker.storage.global_config.stop()

    if self.test_config.storage:
        self.app.broker.storage.stop()

    if self.test_config.broker:
        self.app.broker.stop()

    if self.test_config.worker:
        self.app.worker.stop()