1# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4; encoding:utf8 -*-
2#
3from __future__ import print_function
4from future import standard_library
5standard_library.install_aliases()
6
7import os
8import sys
9import pytest
10
11@pytest.fixture(scope=u"function")
12def redirect_stdin():
13    u"""GPG requires stdin to be open and have real file descriptor, which interferes with pytest's capture facility.
14    Work around this by redirecting /dev/null to stdin temporarily.
15
16    Activate this fixture on unittest test methods and classes by means of @pytest.mark.usefixtures("redirect_stdin")."""
17    try:
18        targetfd_save = os.dup(0)
19        stdin_save = sys.stdin
20
21        nullfile = open(os.devnull, u"r")
22        sys.stdin = nullfile
23        os.dup2(nullfile.fileno(), 0)
24        yield
25    finally:
26        os.dup2(targetfd_save, 0)
27        sys.stdin = stdin_save
28        os.close(targetfd_save)
29        nullfile.close()
30