Skip to content

AsyncTestCase

Async test classes.

AsyncTestCase

Bases: BaseTestCase[Literal[True]]

Asynchronous testing case.

Example

from qtasks import QueueTasks
from qtasks.tests import AsyncTestCase

app = QueueTasks()

test_case = AsyncTestCase(app=app)
Source code in src/qtasks/tests/async_testcase.py
 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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
class AsyncTestCase(BaseTestCase[Literal[True]]):
    """
    Asynchronous testing case.

    ## Example

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

    app = QueueTasks()

    test_case = AsyncTestCase(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,
    ):
        """
        Asynchronous test case.

        Args:
            app(QueueTasks, Doc): 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

        self._global_loop: asyncio.AbstractEventLoop | None = None

    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,
    ):  # TODO: fix!
        """
        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_loop():
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)
            try:
                loop.run_until_complete(self.start(loop=loop, num_workers=num_workers))
            finally:
                loop.close()

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

    async def start(
        self,
        loop: Annotated[
            asyncio.AbstractEventLoop | None,
            Doc("""
                    Asynchronous loop.

                    Default: `None`.
                    """),
        ] = None,
        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:
            loop (asyncio.AbstractEventLoop, optional): async loop. Default: None.
            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(
            loop=loop,
            starter=starter,
            num_workers=num_workers,
            reset_config=reset_config,
        )

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

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

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

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

    async 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.AsyncResult`.

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

    async 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"[AsyncTestCase: {self.name}] Broker is not started!")
            return
        return await self.app.broker.get(uuid=uuid)

__init__(app, name=None)

Asynchronous test case.

Parameters:

Name Type Description Default
app (QueueTasks, Doc)

Main instance.

required
name str

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

None
Source code in src/qtasks/tests/async_testcase.py
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
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,
):
    """
    Asynchronous test case.

    Args:
        app(QueueTasks, Doc): 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

    self._global_loop: asyncio.AbstractEventLoop | None = None

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

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.AsyncResult.

None

Returns:

Type Description
Union[Task, None]

Task|None: Task data or None.

Source code in src/qtasks/tests/async_testcase.py
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
async 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.AsyncResult`.

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

get(uuid) async

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/async_testcase.py
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
async 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"[AsyncTestCase: {self.name}] Broker is not started!")
        return
    return await self.app.broker.get(uuid=uuid)

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

Runs app.run_forever().

Parameters:

Name Type Description Default
loop AbstractEventLoop

async loop. Default: None.

None
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/async_testcase.py
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
async def start(
    self,
    loop: Annotated[
        asyncio.AbstractEventLoop | None,
        Doc("""
                Asynchronous loop.

                Default: `None`.
                """),
    ] = None,
    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:
        loop (asyncio.AbstractEventLoop, optional): async loop. Default: None.
        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(
        loop=loop,
        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/async_testcase.py
 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
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,
):  # TODO: fix!
    """
    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_loop():
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        try:
            loop.run_until_complete(self.start(loop=loop, num_workers=num_workers))
        finally:
            loop.close()

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

stop() async

Stops the test case.

Source code in src/qtasks/tests/async_testcase.py
162
163
164
165
166
167
168
169
170
171
172
173
174
175
async def stop(self):
    """Stops the test case."""
    if self.test_config.global_config and self.app.broker.storage.global_config:
        await self.app.broker.storage.global_config.stop()

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

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

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