jrnl/tests/lib/when_steps.py
Jonathan Wren 2ab485de8c
Improve handling of mocking logic in pytest (#1382)
* WIP

* fix handling of user input (stdin, input, getpass)

* take out redundant pytest step

* fix handling of 'we should' statements

* fix test that doesn't use a config file

* fix another test that uses stdin

Co-authored-by: Micah Jerome Ellison <micah.jerome.ellison@gmail.com>

* remove .tool-versions file per PR feedback

* add comment to clarify why disembodied variables are here

Co-authored-by: Micah Jerome Ellison <micah.jerome.ellison@gmail.com>
2021-12-11 12:35:32 -08:00

56 lines
1.5 KiB
Python

# Copyright (C) 2012-2021 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html
from contextlib import ExitStack
import os
from pytest_bdd import when
from pytest_bdd.parsers import parse
from pytest_bdd.parsers import re
from jrnl.cli import cli
@when(parse('we change directory to "{directory_name}"'))
def when_we_change_directory(directory_name):
if not os.path.isdir(directory_name):
os.mkdir(directory_name)
os.chdir(directory_name)
# These variables are used in the `@when(re(...))` section below
command = '(?P<command>[^"]+)'
input_method = "(?P<input_method>enter|pipe)"
user_input = '(?P<user_input>[^"]+)'
@when(parse('we run "jrnl {command}" and {input_method}\n{user_input}'))
@when(re(f'we run "jrnl {command}" and {input_method} "{user_input}"'))
@when(re(f'we run "jrnl" and {input_method} "{user_input}"'))
@when(parse('we run "jrnl {command}"'))
@when('we run "jrnl"')
def we_run_jrnl(cli_run, capsys, keyring):
from keyring import set_keyring
set_keyring(keyring)
with ExitStack() as stack:
mocks = cli_run["mocks"]
factories = cli_run["mock_factories"]
for id in factories:
mocks[id] = stack.enter_context(factories[id]())
try:
cli()
except StopIteration:
# This happens when input is expected, but don't have any input left
pass
except SystemExit as e:
cli_run["status"] = e.code
captured = capsys.readouterr()
cli_run["stdout"] = captured.out
cli_run["stderr"] = captured.err