Skip to content

Commit

Permalink
Adding input file option (#6)
Browse files Browse the repository at this point in the history
* Adding input file option

* Fix typing that break typer

* fix make file
  • Loading branch information
royreznik authored Feb 9, 2024
1 parent 37406a1 commit 251e622
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 9 deletions.
28 changes: 20 additions & 8 deletions rexi/cli.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import os
import sys
from typing import Annotated, Optional

import typer

Expand All @@ -10,12 +11,23 @@

# noinspection SpellCheckingInspection
@app.command("rexi")
def rexi_cli() -> None:
stdin = sys.stdin.read()
try:
os.close(sys.stdin.fileno())
except OSError:
pass
sys.stdin = open("/dev/tty", "rb") # type: ignore[assignment]
app: RexiApp[int] = RexiApp(stdin)
def rexi_cli(
input_file: Annotated[
Optional[typer.FileText],
typer.Option(
"--input", "-i",
help="Input file to pass to rexi; if not provided, stdin will be used.",
),
] = None,
) -> None:
if input_file:
input_text = input_file.read()
else:
input_text = sys.stdin.read()
try:
os.close(sys.stdin.fileno())
except OSError:
pass
sys.stdin = open("/dev/tty", "rb") # type: ignore[assignment]
app: RexiApp[int] = RexiApp(input_text)
app.run()
16 changes: 15 additions & 1 deletion tests/test_cli.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
from io import BytesIO
from pathlib import Path
from unittest.mock import Mock

from _pytest.monkeypatch import MonkeyPatch
from typer.testing import CliRunner
from rexi.cli import app


def test_app(monkeypatch: MonkeyPatch) -> None:
def test_stdin_cli(monkeypatch: MonkeyPatch) -> None:
"""
Couldn't find a better way to test the CLI without patching everything :(
"""
Expand All @@ -24,3 +25,16 @@ def test_app(monkeypatch: MonkeyPatch) -> None:
open_mock.assert_called_once_with("/dev/tty", "rb")
class_mock.assert_called_once_with(text.decode())
instance_mock.run.assert_called_once()


def test_file_input_cli(monkeypatch: MonkeyPatch, tmp_path: Path) -> None:
runner = CliRunner()
text = "This iS! aTe xt2 F0r T3sT!ng"
(tmp_path / "text_file").write_text(text)
class_mock = Mock()
instance_mock = Mock()
with monkeypatch.context():
class_mock.return_value = instance_mock
monkeypatch.setattr("rexi.cli.RexiApp", class_mock)
runner.invoke(app, args=["-i", str(tmp_path / "text_file")])
class_mock.assert_called_once_with(text)

0 comments on commit 251e622

Please sign in to comment.