summaryrefslogtreecommitdiffstats
path: root/etc/unittest/asyncio.py
blob: e886c43a474ef8fff852ef60cb6e3c2e86be64fb (plain) (blame)
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
56
57
58
59
60
61
62
63
64
65
66
67
import asyncio
try:
    import nest_asyncio
    has_nest_asyncio = True
except:
    has_nest_asyncio = False 
import unittest

import g4f
from g4f import ChatCompletion
from .mocks import ProviderMock, AsyncProviderMock, AsyncGeneratorProviderMock

DEFAULT_MESSAGES = [{'role': 'user', 'content': 'Hello'}]

class TestChatCompletion(unittest.TestCase):

    async def run_exception(self):
        return ChatCompletion.create(g4f.models.default, DEFAULT_MESSAGES, AsyncProviderMock)

    def test_exception(self):
        if hasattr(asyncio, '_nest_patched'):
            self.skipTest('asyncio is already patched')
        self.assertRaises(g4f.errors.NestAsyncioError, asyncio.run, self.run_exception())

    def test_create(self):
        result = ChatCompletion.create(g4f.models.default, DEFAULT_MESSAGES, AsyncProviderMock)
        self.assertEqual("Mock",result)

    def test_create_generator(self):
        result = ChatCompletion.create(g4f.models.default, DEFAULT_MESSAGES, AsyncGeneratorProviderMock)
        self.assertEqual("Mock",result)

class TestChatCompletionAsync(unittest.IsolatedAsyncioTestCase):

    async def test_base(self):
        result = await ChatCompletion.create_async(g4f.models.default, DEFAULT_MESSAGES, ProviderMock)
        self.assertEqual("Mock",result)

    async def test_async(self):
        result = await ChatCompletion.create_async(g4f.models.default, DEFAULT_MESSAGES, AsyncProviderMock)
        self.assertEqual("Mock",result)

    async def test_create_generator(self):
        result = await ChatCompletion.create_async(g4f.models.default, DEFAULT_MESSAGES, AsyncGeneratorProviderMock)
        self.assertEqual("Mock",result)

class TestChatCompletionNestAsync(unittest.IsolatedAsyncioTestCase):

    def setUp(self) -> None:
        if not has_nest_asyncio:
            self.skipTest('"nest_asyncio" not installed')
        nest_asyncio.apply()

    async def test_create(self):
        result = await ChatCompletion.create_async(g4f.models.default, DEFAULT_MESSAGES, ProviderMock)
        self.assertEqual("Mock",result)

    async def test_nested(self):
        result = ChatCompletion.create(g4f.models.default, DEFAULT_MESSAGES, AsyncProviderMock)
        self.assertEqual("Mock",result)

    async def test_nested_generator(self):
        result = ChatCompletion.create(g4f.models.default, DEFAULT_MESSAGES, AsyncGeneratorProviderMock)
        self.assertEqual("Mock",result)

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