# This file was originally generated by PyScripter's unitest wizard

import asyncio
import sys

from ftd2xx.ftd2xx import DeviceError

from .. import aio

if sys.version_info >= (3, 8, 0):
    from unittest import IsolatedAsyncioTestCase
else:
    from aiounittest import AsyncTestCase as IsolatedAsyncioTestCase  # type: ignore


class TestAIOFTD2XX(IsolatedAsyncioTestCase):
    def setUp(self):
        self.device = aio.open()

    def tearDown(self):
        self.device.close()

    async def testread(self):
        self.device.setTimeouts(1000, 0)
        result = await self.device.read(1)
        self.assertIsInstance(result, bytes)

    async def testreadtimeout(self):
        self.device.setTimeouts(1, 0)

        for _ in range(100):
            try:
                await self.device.read(1, exc=True)
                self.device.purge()
                continue
            except Exception as e:
                self.assertIsInstance(e, asyncio.TimeoutError)
                return
        raise Exception("Could not timeout!")


class TestAIOGlobals(IsolatedAsyncioTestCase):
    def testaioopen(self):
        try:
            device = aio.open()
            self.assertIsInstance(device, aio.FTD2XX)
        except AssertionError:
            raise
        else:
            device.close()

    def testaioopenEx(self):
        dev0 = None
        try:
            devices = aio.listDevices()
            if devices is None:
                raise DeviceError("Device not found")
            dev0_id = devices[0]
            dev0 = aio.openEx(dev0_id)
            self.assertIsInstance(dev0, aio.FTD2XX)
        except AssertionError:
            raise
        finally:
            if dev0:
                dev0.close()


# if __name__ == "__main__":
#     unittest.main()
