Skip to content

Commit

Permalink
cleared_argv tests
Browse files Browse the repository at this point in the history
  • Loading branch information
jayqi committed Jun 27, 2020
1 parent e871231 commit e30d287
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
3 changes: 3 additions & 0 deletions nbautoexport/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@

@contextmanager
def cleared_argv():
"""Context manager that temporarily clears sys.argv. Useful for wrapping nbconvert so
unexpected arguments from outer program (e.g., nbautoexport) aren't passed to nbconvert.
"""
prev_argv = [arg for arg in sys.argv]
sys.argv = [sys.argv[0]]
try:
Expand Down
35 changes: 35 additions & 0 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import sys

import pytest

from nbautoexport.utils import cleared_argv


def test_cleared_argv(monkeypatch):
"""cleared_argv context manager clears sys.argv and restores it on exit
"""
mocked_argv = ["nbautoexport", "convert", "the_notebook.ipynb", "-f", "script"]
monkeypatch.setattr(sys, "argv", mocked_argv)

assert sys.argv == mocked_argv

with cleared_argv():
assert sys.argv == mocked_argv[:1]

assert sys.argv == mocked_argv


def test_cleared_argv_with_error(monkeypatch):
"""cleared_argv context manager restores sys.argv even with exception
"""
mocked_argv = ["nbautoexport", "convert", "the_notebook.ipynb", "-f", "script"]
monkeypatch.setattr(sys, "argv", mocked_argv)

assert sys.argv == mocked_argv

with pytest.raises(Exception):
with cleared_argv():
assert sys.argv == mocked_argv[:1]
raise Exception

assert sys.argv == mocked_argv

0 comments on commit e30d287

Please sign in to comment.