#!/usr/bin/python3
# Copyright 2023 Collabora Ltd.
# SPDX-License-Identifier: LGPL-2.0-or-later

from ctypes import CDLL, c_void_p, c_char_p, get_errno
from errno import ENOSYS
from unittest import TestCase, main


class TestLibudev0(TestCase):
    def setUp(self):
        self.libudev0 = CDLL("libudev.so.0", use_errno=True)

    def test_libudev1_functions(self):
        '''
        libudev.so.0 exposes libudev.so.1 functions

        https://github.com/archlinux/libudev0-shim/pull/3
        '''
        new = self.libudev0.udev_new
        new.argtypes = []
        new.restype = c_void_p
        unref = self.libudev0.udev_unref
        unref.argtypes = [c_void_p]
        unref.restype = None
        udev = new()
        self.assertIsNotNone(udev)
        unref(udev)

    def test_udev_get_run_path(self):
        '''A working implementation is provided'''
        f = self.libudev0.udev_get_run_path
        f.argtypes = [c_void_p]
        f.restype = c_char_p
        self.assertEqual(f(None), b"/run/udev")

    def test_udev_get_dev_path(self):
        '''A working implementation is provided'''
        f = self.libudev0.udev_get_dev_path
        f.argtypes = [c_void_p]
        f.restype = c_char_p
        self.assertEqual(f(None), b"/dev")

    def test_udev_get_sys_path(self):
        '''A working implementation is provided'''
        f = self.libudev0.udev_get_sys_path
        f.argtypes = [c_void_p]
        f.restype = c_char_p
        self.assertEqual(f(None), b"/sys")

    def test_udev_queue_get_failed_list_entry(self):
        '''A stub implementation is provided'''
        f = self.libudev0.udev_queue_get_failed_list_entry
        f.argtypes = [c_void_p]
        f.restype = c_void_p
        self.assertIsNone(f(None))
        self.assertEqual(get_errno(), ENOSYS)

    def test_udev_monitor_new_from_socket(self):
        '''A stub implementation is provided'''
        f = self.libudev0.udev_monitor_new_from_socket
        f.argtypes = [c_void_p, c_char_p]
        f.restype = c_void_p
        self.assertIsNone(f(None, b"/nonexistent"))
        self.assertEqual(get_errno(), ENOSYS)


if __name__ == '__main__':
    main(verbosity=2)
