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 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
|
import logging
import pytest
import sys
class InputMock(object):
"""A replacement for input() or raw_input() respectively.
This mock, when called, mimics input() behaviour, outputs a prompt,
etc., but does not wait for real key strokes. Instead it returns the
next value from `fake_input_values` given on initialization:
>>> faked_input = InputMock(["val1", "val2", "1"])
>>> faked_input("Give a value: ")
Give a value: val1
'val1'
>>> faked_input("And another value: ")
And another value: val2
'val2'
>>> faked_input()
1
'1'
To be used with the `monkeypatch` pytest fixture, to replace
`diceware.random_sources.input_func`.
"""
fake_input_values = []
def __init__(self, fake_input_values=[]):
self.fake_input_values = fake_input_values
self.fake_input_values.reverse()
def __call__(self, prompt=''):
curr_value = self.fake_input_values.pop()
print("%s%s" % (prompt, curr_value))
return curr_value
@pytest.fixture(scope="function")
def argv_handler(request):
"""This fixture restores sys.argv and sys.stdin after tests.
"""
_argv_stored = sys.argv
_stdin_stored = sys.stdin
def teardown():
sys.argv = _argv_stored
sys.stdin = _stdin_stored
request.addfinalizer(teardown)
@pytest.fixture(scope="function")
def wordlists_dir(request, monkeypatch, tmpdir):
"""This fixture provides a temporary wordlist dir.
"""
monkeypatch.setattr(
"diceware.wordlist.get_wordlist_dirs", lambda: [str(tmpdir)])
return tmpdir
@pytest.fixture(scope="function")
def home_dir(request, monkeypatch, tmpdir):
"""This fixture provides a temporary user home.
"""
tmpdir.mkdir("home")
monkeypatch.setenv("HOME", str(tmpdir / "home"))
return tmpdir / "home"
@pytest.fixture(autouse=True)
def change_home(monkeypatch, tmpdir):
"""Set $HOME to some tempdir.
This is an autouse fixture.
If the user running tests has an own .diceware.ini in his home, then
this will influence tests. Therefore we set the user home to some
empty dir while tests are running.
The same applies for XDG-based config files, that might be set on the host
running and point to real config files not related to testing.
"""
monkeypatch.setenv("HOME", str(tmpdir))
monkeypatch.delenv("XDG_CONFIG_DIRS", raising=False)
monkeypatch.delenv("XDG_CONFIG_HOME", raising=False)
monkeypatch.delenv("XDG_DATA_DIRS", raising=False)
monkeypatch.delenv("XDG_DATA_HOME", raising=False)
return tmpdir
@pytest.fixture(autouse=True)
def cleanup_loghandlers(request, monkeypatch):
"""Clean up log handlers still in `ulif.diceware` logger
"""
def teardown():
logger = logging.getLogger('ulif.diceware')
for handler in logger.handlers:
logger.removeHandler(handler)
request.addfinalizer(teardown)
|