pywincffi/dev/testutil.py
class TestCase(_TestCase):  # pylint: disable=too-many-public-methods
    """
    A base class for all test cases.  By default the
    core test case just provides some extra functionality.
    """
    # A list of hosts and port to check for internet access on.  If we fail
    # to reach any of the hosts in `INTERNET_HOSTS` on `INTERNET_PORT` then
    # `HAS_INTERNET` will be set to False.
    INTERNET_PORT = 80
    INTERNET_HOSTS = ("github.com", "readthedocs.org", "example.com")
    REQUIRES_INTERNET = False
    HAS_INTERNET = None

    # Class level attributes used to access some specific Windows API
    # functions when testing.  This is kept separate from what `dist.load()`
    # produces so problems in the build don't break parts of the base TestCase.
    ffi = None
    kernel32 = None
    ws2_32 = None

    @classmethod
    def setUpClass(cls):
        # Reset everything back to the default values first.
        cls.ffi = None
        cls.kernel32 = None
        cls.ws2_32 = None
        cls.HAS_INTERNET = None

        # First run and this test case requires internet access.  Determine
        # if we have access to the internet then cache the value.
        if cls.REQUIRES_INTERNET and SharedState.HAS_INTERNET is None:
            original_timeout = socket.getdefaulttimeout()
            socket.setdefaulttimeout(1)

            try:
                for hostname in cls.INTERNET_HOSTS:
                    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                    try:
                        sock.connect((hostname, cls.INTERNET_PORT))
                        SharedState.HAS_INTERNET = True
                        break

                    # pylint: disable=broad-except
                    except Exception:  # pragma: no cover
                        pass

                    finally:
                        sock.close()
                else:  # pragma: no cover
                    SharedState.HAS_INTERNET = False
            finally:
                socket.setdefaulttimeout(original_timeout)

        if os.name == "nt" and SharedState.ffi is None:
            try:
                ffi = FFI()
                ffi.set_unicode(True)
                ffi.cdef(dedent("""
                // kernel32 functions
                DWORD GetLastError(void);
                void SetLastError(DWORD);

                // ws2_32 functions
                void WSASetLastError(int);
                int WSAGetLastError(void);
                """))
                SharedState.ffi = ffi
                SharedState.kernel32 = ffi.dlopen("kernel32")
                SharedState.ws2_32 = ffi.dlopen("ws2_32")

            # pylint: disable=broad-except
            except Exception as error:  # pragma: no cover
                if os.name == "nt":
                    SharedState.ffi = error

        cls.HAS_INTERNET = SharedState.HAS_INTERNET
        cls.ffi = SharedState.ffi
        cls.kernel32 = SharedState.kernel32
        cls.ws2_32 = SharedState.ws2_32

    def setUp(self):  # pragma: no cover
        if self.REQUIRES_INTERNET and not self.HAS_INTERNET:
            if os.environ.get("CI"):
                self.fail(
                    "%s requires internet but we do not seem to be "
                    "connected." % self.__class__.__name__)

            self.skipTest("Internet unavailable")

        if os.name != "nt":
            return

        if isinstance(self.ffi, Exception):
            self.fail("FFI module setup failed: %s" % self.ffi)

        self.assertIsNotNone(
            self.kernel32, "setUp() failed: missing kernel32")
        self.assertIsNotNone(
            self.ws2_32, "setUp() failed: missing ws2_32")

        self.addCleanup(self.unhandled_error_check)

        # Always reset the last error to 0 between tests.  This ensures
        # that if an unhandled API error occurs it won't impact the
        # currently running test.  The cleanup step above will ensure that
        # tests that do not exit cleanly will cause a failure.
        self.kernel32.SetLastError(0)
        self.ws2_32.WSASetLastError(0)

    def GetLastError(self):  # pylint: disable=invalid-name
        """
        Returns a tuple containing output from the Windows GetLastError
        function and the associated error message.  The error message will
        be None if GetLastError() returns 0.
        """
        errno = self.kernel32.GetLastError()
        return errno, self.ffi.getwinerror(errno) if errno != 0 else None

    def WSAGetLastError(self):  # pylint: disable=invalid-name
        """
        Returns a tuple containing output from the Windows WSAGetLastError
        function and the associated error message.  The error message will
        be None if WSAGetLastError() returns 0.
        """
        errno = self.ws2_32.WSAGetLastError()
        return errno, self.ffi.getwinerror(errno) if errno != 0 else None

    def WSASetLastError(self, errno):  # pylint: disable=invalid-name
        """Wrapper for WSASetLastError()"""
        self.ws2_32.WSASetLastError(errno)

    def SetLastError(self, errno):  # pylint: disable=invalid-name
        """Wrapper for SetLastError()"""
        self.kernel32.SetLastError(errno)

    def unhandled_error_check(self):
        """
        A cleanup step which ensures that there are not any uncaught API
        errors left over.  Unhandled errors could be a sign of an unhandled
        testing artifact, improper API usage or other problem.  In any case,
        unhandled errors are often a source of test flake.
        """
        # Check for kernel32 errors.
        k32_errno, k32_message = self.GetLastError()
        self.assertEqual(
            k32_errno, 0,
            msg="Unhandled kernel32 error. Errno: %r. Message: %r" % (
                k32_errno, k32_message))

        # Check for ws2_32 errors.
        ws2_errno, ws2_message = self.WSAGetLastError()
        self.assertEqual(
            ws2_errno, 0,
            msg="Unhandled ws2_32 error. Errno: %r. Message: %r" % (
                ws2_errno, ws2_message))

    def _terminate_process(self, process):  # pylint: disable=no-self-use
        """
        Calls terminnate() on ``process`` and ignores any errors produced.
        """
        try:
            process.terminate()

        # pylint: disable=broad-except
        except Exception:  # pragma: no cover
            pass

    def create_python_process(self, command):
        """Creates a Python process that run ``command``"""
        process = subprocess.Popen(
            [sys.executable, "-c", command],
            stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        self.addCleanup(self._terminate_process, process)
        return process

    def random_string(self, length):
        """
        Returns a random string as long as ``length``.  The first character
        will always be a letter.  All other characters will be A-F,
        A-F or 0-9.
        """
        if length < 1:  # pragma: no cover
            self.fail("Length must be at least 1.")

        # First character should always be a letter so the string
        # can be used in object names.
        output = choice(ascii_lowercase)
        length -= 1

        while length:
            length -= 1
            output += choice(ascii_lowercase + ascii_uppercase + "0123456789")

        return output

    def assert_last_error(self, errno):
        """
        This function will assert that the last unhandled error
        was ``errno``.  After the check the last error will be reset to
        zero.

        :param int errno:
            The expected value from GetLastError.
        """
        last_error, _ = self.GetLastError()
        self.assertEqual(last_error, errno)
        self.SetLastError(0)

    def maybe_assert_last_error(self, errno):
        """
        This function is similar to :meth:`assert_last_error` except
        it won't fail if the current error number is already 0.
        """
        last_error, _ = self.GetLastError()
        self.assertIn(last_error, (0, errno))
        self.SetLastError(0)
pywincffi/kernel32/events.py
def SetEvent(hEvent):
    """
    Sets the specified event object to the signaled state.

    .. seealso::

        https://msdn.microsoft.com/en-us/library/ms686211

    :param pywincffi.wintypes.HANDLE hEvent:
        A handle to the event object. The handle must have the
        ``EVENT_MODIFY_STATE`` access right.
    """
    input_check("hEvent", hEvent, HANDLE)

    _, library = dist.load()
    code = library.SetEvent(wintype_to_cdata(hEvent))
    error_check("SetEvent", code=code, expected=NON_ZERO)
pywincffi/kernel32/events.py
def CreateEvent(
        lpEventAttributes=None, bManualReset=True, bInitialState=False,
        lpName=None):
def OpenEvent(dwDesiredAccess, bInheritHandle, lpName):
def ResetEvent(hEvent):
def SetEvent(hEvent):
pywincffi/kernel32/events.py
def OpenEvent(dwDesiredAccess, bInheritHandle, lpName):
    """
    Opens an existing named event.

    .. seealso::

        https://msdn.microsoft.com/en-us/library/ms684305

    :param int dwDesiredAccess:
        The access desired for the event object.

    :param bool bInheritHandle:
    :param str lpName:
        Type is ``unicode`` on Python 2, ``str`` on Python 3.

    :return:
        Returns a :class:`pywincffi.wintypes.HANDLE` to the event.
    """
    input_check("dwDesiredAccess", dwDesiredAccess, integer_types)
    input_check("bInheritHandle", bInheritHandle, bool)
    input_check("lpName", lpName, text_type)

    ffi, library = dist.load()

    handle = library.OpenEvent(
        ffi.cast("DWORD", dwDesiredAccess),
        ffi.cast("BOOL", bInheritHandle),
        lpName
    )
    error_check("OpenEvent")
    return HANDLE(handle)
pywincffi/kernel32/events.py
def ResetEvent(hEvent):
    """
    Sets the specified event object to the nonsignaled state.

    .. seealso::

        https://msdn.microsoft.com/en-us/library/ms684305

    :param pywincffi.wintypes.HANDLE hEvent:
        A handle to the event object to be reset. The handle must
        have the ``EVENT_MODIFY_STATE`` access right.
    """
    input_check("hEvent", hEvent, HANDLE)

    _, library = dist.load()
    code = library.ResetEvent(wintype_to_cdata(hEvent))
    error_check("ResetEvent", code=code, expected=NON_ZERO)
pywincffi/kernel32/synchronization.py
def WaitForSingleObject(hHandle, dwMilliseconds):
    """
    Waits for the specified object to be in a signaled state
    or for ``dwMiliseconds`` to elapse.

    .. seealso::

        https://msdn.microsoft.com/en-us/library/ms687032

    :param pywincffi.wintypes.HANDLE hHandle:
        The handle to wait on.

    :param int dwMilliseconds:
        The time-out interval.
    """
    input_check("hHandle", hHandle, HANDLE)
    input_check("dwMilliseconds", dwMilliseconds, integer_types)

    ffi, library = dist.load()
    result = library.WaitForSingleObject(
        wintype_to_cdata(hHandle), ffi.cast("DWORD", dwMilliseconds)
    )

    if result == library.WAIT_FAILED:
        raise WindowsAPIError(
            "WaitForSingleObject", "Wait Failed", ffi.getwinerror()[-1],
            return_code=result, expected_return_code="not %s" % result)

    error_check("WaitForSingleObject")

    return result
pywincffi/exceptions.py
class InputError(PyWinCFFIError):
    """
    A subclass of :class:`PyWinCFFIError` that's raised when invalid input
    is provided to a function.  Because we're passing inputs to C we have
    to be sure that the input(s) being provided are what we're expecting so
    we fail early and provide better error messages.

    :param str name:
        The name of the parameter being checked.

    :param value:
        The value of the parameter being checked.

    :keyword allowed_types:
        The expected type(s). If provided then the exception's message will
        be tailored to provide information about ``value``'s type and the
        possible input types.

    :keyword allowed_values:
        The expected value(s).  If provided then the exception's message will
        be tailored to provide information about what value(s) were allowed
        for ``value``.

    :keyword ffi:
        If ``value`` is a C object, ``ffi`` is provided and ``allowed_types``
        is provided as well then the provided ``ffi`` instance will be used
        to provide additional context.

    :keyword str message:
        A custom error message.  This will override the default error messages
        which :class:`InputError` would normally generate.  This can be
        helpful if there is a problem with a given input parameter to a
        function but it's unrelated to the type of input.
    """
    def __init__(  # pylint: disable=too-many-arguments
            self, name, value,
            allowed_types=None, allowed_values=None, ffi=None, message=None):
        if allowed_types is not None and allowed_values is not None:
            raise ValueError(
                "Please provide either `allowed_types` or `allowed_values`")

        if (allowed_types is None and allowed_values is None and
                message is None):
            raise ValueError(
                "Please provide `allowed_types`, `allowed_values` or "
                "`message`")

        self.name = name
        self.value = value
        self.allowed_types = allowed_types
        self.allowed_values = allowed_values
        self.message = message

        if self.message is None and self.allowed_types is not None:
            if ffi is None:
                typeof = repr(type(value))
            else:
                try:
                    ffi_exceptions = (TypeError, CDefError, ffi.error)
                except AttributeError:  # pragma: no cover
                    ffi_exceptions = (TypeError, CDefError)

                try:
                    typeof = ffi.typeof(value)
                except ffi_exceptions:
                    typeof = repr(type(value))
                else:
                    typeof = "{classname}(kind={kind}, cname={cname})".format(
                        classname=value.__class__.__name__,
                        kind=repr(typeof.kind), cname=repr(typeof.cname))

            self.message = \
                "Expected type(s) {expected} for {name}. Type of {name} " \
                "is {typeof}.".format(
                    expected=repr(allowed_types), name=repr(name),
                    typeof=typeof)

        elif self.message is None and self.allowed_values is not None:
            self.message = \
                "Expected the value of {name} to be in {values}. Value of " \
                "{name} is {value}.".format(
                    name=repr(name), values=allowed_values, value=repr(value))

        super(InputError, self).__init__(self.message)
pywincffi/core/dist.py
MODULE_NAME = "_pywincffi"
HEADER_FILES = (
    resource_filename(
        "pywincffi", join("core", "cdefs", "headers", "typedefs.h")),
    resource_filename(
        "pywincffi", join("core", "cdefs", "headers", "constants.h")),
    resource_filename(
        "pywincffi", join("core", "cdefs", "headers", "structs.h")),
    resource_filename(
        "pywincffi", join("core", "cdefs", "headers", "functions.h")))
SOURCE_FILES = (
    resource_filename(
        "pywincffi", join("core", "cdefs", "sources", "main.c")), )
LIBRARIES = ("kernel32", "user32", "Ws2_32")
REGEX_SAL_ANNOTATION = re.compile(
    r"\b(_In_|_Inout_|_Out_|_Outptr_|_Reserved_)(opt_)?\b")
    _RUNTIME_CONSTANTS = dict(
        # Defined here because cffi can't handle negative values
        # in constants yet.
        INVALID_HANDLE_VALUE=-1,

        # The maximum length of the lpCommandLine input to a CreateProcess
        # call:
        #  https://msdn.microsoft.com/en-us/library/ms682425
        # Technically, this is not a Windows constant.  It's something that
        # pywincffi defines for ease of use and to limit the possibility of
        # typos.
        MAX_COMMAND_LINE=32768
    )
class LibraryWrapper(object):  # pylint: disable=too-few-public-methods
class Loader(object):
    def __init__(self, library):
    def __dir__(self):
    def __getattribute__(self, item):
    def __getattr__(self, item):
    def __repr__(self):  # pragma: no cover
    def set(cls, ffi, library):
    def get(cls):
def _import_path(path, module_name=MODULE_NAME):
def _read(*paths):
def _ffi(
        module_name=MODULE_NAME, headers=HEADER_FILES, sources=SOURCE_FILES,
        libraries=LIBRARIES):
def _compile(ffi, tmpdir=None, module_name=MODULE_NAME):
def load():
pywincffi/kernel32/events.py
def CreateEvent(
        lpEventAttributes=None, bManualReset=True, bInitialState=False,
        lpName=None):
    """
    Creates or opens an named or unnamed event object.

    .. seealso::

        https://msdn.microsoft.com/en-us/library/ms682396

    :keyword :class:`pywincffi.wintypes.SECURITY_ATTRIBUTES` lpEventAttributes:
        If not provided then, by default, the handle cannot be inherited
        by a subprocess.

    :keyword bool bManualReset:
        If True then this function will create a manual reset
        event which must be manually reset with :func:`ResetEvent`.  Refer
        to the msdn documentation for full information.

        **Default:** ``True``

    :keyword bool bInitialState:
        If True the initial state will be 'signaled'.

        **Default:** ``False``

    :keyword str lpName:
        Type is ``unicode`` on Python 2, ``str`` on Python 3.
        The optional case-sensitive name of the event.  If not provided then
        the event will be created without an explicit name.

    :returns:
        Returns a :class:`pywincffi.wintypes.HANDLE` to the event. If an event
        by the given name already exists then it will be returned instead of
        creating a new event.
    """
    input_check("bManualReset", bManualReset, bool)
    input_check("bInitialState", bInitialState, bool)

    ffi, library = dist.load()

    if lpName is None:
        lpName = ffi.NULL
    else:
        input_check("lpName", lpName, text_type)

    input_check(
        "lpEventAttributes", lpEventAttributes,
        allowed_types=(SECURITY_ATTRIBUTES, NoneType)
    )

    handle = library.CreateEvent(
        wintype_to_cdata(lpEventAttributes),
        ffi.cast("BOOL", bManualReset),
        ffi.cast("BOOL", bInitialState),
        lpName
    )

    try:
        error_check("CreateEvent")
    except WindowsAPIError as error:
        if error.errno != library.ERROR_ALREADY_EXISTS:
            raise

    return HANDLE(handle)
pywincffi/kernel32/handle.py
def CloseHandle(hObject):
    """
    Closes an open object handle.

    .. seealso::

        https://msdn.microsoft.com/en-us/library/ms724211

    :type hObject: pywincffi.wintypes.HANDLE or pywincffi.wintypes.SOCKET
    :param hObject:
        The handle object to close.
    """
    input_check("hObject", hObject, (HANDLE, SOCKET))
    _, library = dist.load()

    code = library.CloseHandle(wintype_to_cdata(hObject))
    error_check("CloseHandle", code=code, expected=NON_ZERO)
pywincffi/exceptions.py
class WindowsAPIError(PyWinCFFIError):
    """
    A subclass of :class:`PyWinCFFIError` that's raised when there was a
    problem calling a Windows API function.

    :param str function:
        The Windows API function being called when the error was raised.

    :param str error:
        A string representation of the error message.

    :param int errno:
        An integer representing the error.  This usually represents
        a constant which Windows has produced in response to a problem.

    :keyword int return_code:
        If the return value of a function has been checked the resulting
        code will be set as this value.

    :keyword int expected_return_code:
        The value we expected to receive for ``code``.
    """
    # pylint: disable=too-many-arguments
    def __init__(self, function, error, errno,
                 return_code=None, expected_return_code=None):
        self.function = function
        self.error = error
        self.errno = errno
        self.return_code = return_code
        self.expected_return_code = expected_return_code

        if return_code is None and expected_return_code is None:
            self.message = \
                "Error when calling {0}. Message from Windows API was " \
                "{1!r} (errno: {2}).".format(self.function, self.error, errno)

        elif return_code is not None and expected_return_code is not None:
            self.message = (
                "Error when calling {0}.  Expected to receive {1!r} from {2} "
                "but got {3!r} instead. (error: {4!r})".format(
                    self.function, self.return_code, self.function,
                    self.expected_return_code, self.error
                )
            )

        # Generic implementation which we should probably handle
        # better so throw a warning.
        else:  # pragma: no cover
            warnings.warn(Warning(), "Pre-formatting not available")
            self.message = (
                "Error when calling {0}. (error: {1}, errno: {2}, "
                "return_code: {3!r}, expected_return_code: {4!r})".format(
                    self.function, self.error, self.errno, self.return_code,
                    self.expected_return_code
                )
            )

        super(WindowsAPIError, self).__init__(self.message)

    def __repr__(self):
        return (
            "{0}({1!r}, {2!r}, {3!r}, return_code={4!r}, "
            "expected_return_code={5!r})".format(
                self.__class__.__name__, self.function, self.error,
                self.errno, self.return_code, self.expected_return_code))


Question: import sys
from mock import patch
from pywincffi.core import dist
from pywincffi.dev.testutil import TestCase
from pywincffi.exceptions import WindowsAPIError, InputError
from pywincffi.kernel32 import events  # used by mocks
from pywincffi.kernel32 import (
    CloseHandle, CreateEvent, OpenEvent, ResetEvent, WaitForSingleObject,
    SetEvent)




# These tests cause TestPidExists and others to fail under Python 3.4 so for
# now we skip these tests.  Because we're only testing CreateEvent, and
# TestPidExists worked before TestCreateEvent exists, we'll skip these
# for now.
#  Traceback (most recent call last):
# [...]
#    File "c:\python34\lib\subprocess.py", line 754, in __init__
#      _cleanup()
#    File "c:\python34\lib\subprocess.py", line 474, in _cleanup
#      res = inst._internal_poll(_deadstate=sys.maxsize)
#    File "c:\python34\lib\subprocess.py", line 1147, in _internal_poll
#      if _WaitForSingleObject(self._handle, 0) == _WAIT_OBJECT_0:
#  OSError: [WinError 6] The handle is invalid
# TODO: Need to figure out why this happens ^^^
class TestCreateEvent(TestCase):
    """
    Tests for :func:`pywincffi.kernel32.CreateEvent`
    """
    def setUp(self):
        super(TestCreateEvent, self).setUp()
        if sys.version_info[0:2] == (3, 4):
            self.skipTest("Skipped on Python 3.4, see comments.")

    def test_create_event_valid_handle(self):
        handle = CreateEvent(bManualReset=False, bInitialState=False)

Answer:         CloseHandle(handle)  # will raise exception if the handle is invalid