aboutsummaryrefslogtreecommitdiffstats
path: root/sources/pyside6/tests/QtAsyncio/bug_2790.py
blob: 5bf91931e7f7a80b0f01ce36961a2035bf2a603a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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
# Copyright (C) 2024 The Qt Company Ltd.
# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0
from __future__ import annotations

'''Test cases for QtAsyncio'''

import os
import sys
import unittest

from pathlib import Path
sys.path.append(os.fspath(Path(__file__).resolve().parents[1]))
from init_paths import init_test_paths
init_test_paths(False)

import asyncio
import PySide6.QtAsyncio as QtAsyncio


class QAsyncioTestCaseBug2790(unittest.TestCase):

    async def producer(self, products: list[str]):
        while True:
            products.append("product")
            await asyncio.sleep(2)

    async def task(self, outputs: list[str]):
        products = []
        asyncio.ensure_future(self.producer(products))
        for _ in range(6):
            try:
                async with asyncio.timeout(0.5):
                    while len(products) == 0:
                        await asyncio.sleep(0)
                    outputs.append(products.pop(0))
            except TimeoutError:
                outputs.append("Timeout")

    @unittest.skipIf(sys.version_info < (3, 11), "requires asyncio.timeout")
    def test_timeout(self):
        # The Qt event loop (and thus QtAsyncio) does not guarantee that events
        # will be processed in the order they were posted, so there is two
        # possible outputs for this test.
        outputs_expected_1 = ["product", "Timeout", "Timeout", "Timeout", "Timeout", "product"]
        outputs_expected_2 = ["product", "Timeout", "Timeout", "Timeout", "product", "Timeout"]

        outputs_real = []

        QtAsyncio.run(self.task(outputs_real), keep_running=False)

        self.assertTrue(outputs_real in [outputs_expected_1, outputs_expected_2])


if __name__ == '__main__':
    unittest.main()