Skip to content
This repository has been archived by the owner on Jan 29, 2025. It is now read-only.

Commit

Permalink
Added test cases for offline functions (#207)
Browse files Browse the repository at this point in the history
* Added test cases

* fixed error
  • Loading branch information
tannuiscoding authored Nov 9, 2024
1 parent 48e4e01 commit a2ea6b2
Show file tree
Hide file tree
Showing 8 changed files with 172 additions and 225 deletions.
4 changes: 2 additions & 2 deletions package/offline/clip.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import os
from package.offline.support import copy_to_clipboard
from package.offline.support import display
from package.offline.support.copy_to_clipboard import copy_to_clipboard
from package.offline.support.display import display


def clip(snippet_name, password):
Expand Down
2 changes: 1 addition & 1 deletion package/offline/support/display.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import os
from package.offline.support import copy_to_clipboard
from package.offline.support.copy_to_clipboard import copy_to_clipboard
from package.password import valid_password


Expand Down
Empty file removed package/stash/__init__.py
Empty file.
1 change: 0 additions & 1 deletion package/stash/test.py

This file was deleted.

33 changes: 10 additions & 23 deletions tests/test_clip.py
Original file line number Diff line number Diff line change
@@ -1,27 +1,14 @@
import os
import pytest
from package.clip import display
from datetime import datetime
import subprocess
from package.clip import copy_to_clipboard
from unittest.mock import patch, mock_open
from package.offline.support import display
from package.offline.clip import clip
from package.password import valid_password


def test_display_right_password():
current_time = datetime.now().strftime("%H%M")
assert display("test", current_time) is None
def test_clip_invalid_password():
snippet_name = "test_snippet.txt"
password = "invalid_password"


def test_display_wrong_password():
with pytest.raises(ValueError, match="Invalid password"):
display("test", 1111)


def test_copy_to_clipboard(monkeypatch):
def mock_run(*args, **kwargs):
pass

monkeypatch.setattr(subprocess, "run", mock_run)

try:
copy_to_clipboard("Whatever test")
except Exception:
pytest.fail("Unexpected error raised: {e}")
with pytest.raises(ValueError, match="Incorrect password"):
clip(snippet_name, password)
134 changes: 47 additions & 87 deletions tests/test_display.py
Original file line number Diff line number Diff line change
@@ -1,119 +1,79 @@
import pytest
from datetime import datetime
from package.display import show, write
from unittest.mock import Mock
from package.offline.support.display import display


# Mock datetime class
# Mock datetime class for fixed time
class MockDateTime(datetime):
@classmethod
def now(cls):
return datetime.strptime("1234", "%H%M") # Mock time to 12:34
return datetime.strptime("1430", "%H%M")


# Mock file operations
def mock_glob_single_file(*args, **kwargs):
return ["test_file.txt"]
class MockFile:
def __enter__(self):
return self

def __exit__(self, *args):
pass

def mock_glob_no_file(*args, **kwargs):
return []
def read(self):
return "Sample content"


def mock_glob_multiple_files(*args, **kwargs):
return ["test1.txt", "test2.txt"]
@pytest.fixture
def mock_env(monkeypatch):
# Set up environment mocks
monkeypatch.setattr("package.password.datetime", MockDateTime)
monkeypatch.setattr("builtins.open", lambda *args, **kwargs: MockFile())
monkeypatch.setattr("package.offline.support.copy_to_clipboard", lambda x: None)
monkeypatch.setattr("builtins.print", lambda x: None)


def mock_open_file_content(*args, **kwargs):
class MockFile:
def __enter__(self):
return self
def test_display_correct_password(mock_env):
display("test.txt", 1430, "display")

def __exit__(self, *args):
pass

def read(self):
return "Sample content"
def test_display_incorrect_password(mock_env):
with pytest.raises(ValueError, match="Incorrect password"):
display("test.txt", 1431, "display")

return MockFile()

def test_display_wrong_password_type(mock_env):
with pytest.raises(ValueError, match="Incorrect password"):
display("test.txt", "1430", "display")

# Mock subprocess for clipboard operations
def mock_subprocess_run(*args, **kwargs):
return None


# Test cases for show function
def test_show_correct_password(monkeypatch):
monkeypatch.setattr("package.show.datetime", MockDateTime)
monkeypatch.setattr("glob.glob", mock_glob_single_file)
monkeypatch.setattr("builtins.open", mock_open_file_content)
def test_display_file_not_found(mock_env, monkeypatch):
def mock_open(*args, **kwargs):
raise FileNotFoundError()

# Should not raise any exception
show("test_snippet", "1234")
monkeypatch.setattr("builtins.open", mock_open)
mock_print = Mock()
monkeypatch.setattr("builtins.print", mock_print)

display("nonexistent.txt", 1430, "display")
mock_print.assert_called_once_with("Error: No file found with the specified name.")

def test_show_incorrect_password(monkeypatch):
monkeypatch.setattr("package.show.datetime", MockDateTime)

with pytest.raises(ValueError, match="syntax error: incorrect password"):
show("test_snippet", "5678")
def test_display_general_error(mock_env, monkeypatch):
def mock_open(*args, **kwargs):
raise Exception("Test error")

monkeypatch.setattr("builtins.open", mock_open)
mock_print = Mock()
monkeypatch.setattr("builtins.print", mock_print)

# Test cases for clipboard functionality
def test_show_with_clipboard_linux(monkeypatch):
monkeypatch.setattr("package.show.datetime", MockDateTime)
monkeypatch.setattr("glob.glob", mock_glob_single_file)
monkeypatch.setattr(
"package.show.glob.glob", mock_glob_single_file
) # Added this line
monkeypatch.setattr("builtins.open", mock_open_file_content)
monkeypatch.setattr("sys.platform", "linux")
monkeypatch.setattr("shutil.which", lambda x: "/usr/bin/xclip")
monkeypatch.setattr("subprocess.run", mock_subprocess_run)
display("test.txt", 1430, "display")
mock_print.assert_called_once_with("Error: Test error")

show("test_snippet", "1234", clipboard=1)

def test_display_content(mock_env, monkeypatch):
mock_print = Mock()
monkeypatch.setattr("builtins.print", mock_print)

def test_show_with_clipboard_windows(monkeypatch):
monkeypatch.setattr("package.show.datetime", MockDateTime)
monkeypatch.setattr("glob.glob", mock_glob_single_file)
monkeypatch.setattr(
"package.show.glob.glob", mock_glob_single_file
) # Added this line
monkeypatch.setattr("builtins.open", mock_open_file_content)
monkeypatch.setattr("sys.platform", "win32")
monkeypatch.setattr("subprocess.run", mock_subprocess_run)
display("test.txt", 1430, "display")
mock_print.assert_called_once_with("Sample content")

show("test_snippet", "1234", clipboard=1)


def test_show_with_clipboard_macos(monkeypatch):
monkeypatch.setattr("package.show.datetime", MockDateTime)
monkeypatch.setattr("glob.glob", mock_glob_single_file)
monkeypatch.setattr(
"package.show.glob.glob", mock_glob_single_file
) # Added this line
monkeypatch.setattr("builtins.open", mock_open_file_content)
monkeypatch.setattr("sys.platform", "darwin")
monkeypatch.setattr("subprocess.run", mock_subprocess_run)

show("test_snippet", "1234", clipboard=1)


# Test cases for write function
def test_write_correct_password(monkeypatch):
monkeypatch.setattr("package.write.datetime", MockDateTime)
monkeypatch.setattr("glob.glob", mock_glob_single_file)
monkeypatch.setattr(
"package.write.glob.glob", mock_glob_single_file
) # Added this line
monkeypatch.setattr("shutil.copyfile", lambda x, y: None)

write("test_snippet", "1234")


def test_write_incorrect_password(monkeypatch):
monkeypatch.setattr("package.write.datetime", MockDateTime)

with pytest.raises(ValueError, match="syntax error: incorrect password"):
write("test_snippet", "5678")
105 changes: 59 additions & 46 deletions tests/test_show.py
Original file line number Diff line number Diff line change
@@ -1,47 +1,60 @@
import pytest
import sys
from datetime import datetime
from package.show import display, copy_to_clipboard


# Mock datetime class
class MockDateTime(datetime):
@classmethod
def now(cls):
return datetime.strptime("1234", "%H%M") # Mock time to 12:34


# Mock functions for clipboard operations
def mock_subprocess_run(*args, **kwargs):
return None # Assume successful run


def mock_open_file_content(*args, **kwargs):
class MockFile:
def __enter__(self):
return self

def __exit__(self, *args):
pass

def read(self):
return "Sample content"

return MockFile()


def test_display_incorrect_password(monkeypatch):
monkeypatch.setattr("package.show.datetime", MockDateTime) # Mock datetime

snippet_name = "test"
incorrect_password = "1111" # Different from "1234"

with pytest.raises(ValueError, match="syntax error: incorrect password"):
display(snippet_name, incorrect_password)


def test_copy_to_clipboard_unsupported_os(monkeypatch):
monkeypatch.setattr(sys, "platform", "unsupported_os")

with pytest.raises(OSError, match="Unsupported operating system"):
copy_to_clipboard("test content")
import os
from unittest.mock import Mock, mock_open, patch
from package.offline.show import show
from package.offline.support.display import display

@pytest.fixture
def setup_test_env(monkeypatch):
base_dir = os.path.dirname(__file__)
snippets_dir = os.path.join(base_dir, "stash")
test_snippet = "test_content"

mock_list = Mock()
mock_clipboard = Mock()
monkeypatch.setattr("package.offline.support.list_snippets", mock_list)
monkeypatch.setattr("package.offline.support.copy_to_clipboard", mock_clipboard)

mock_dt = Mock()
mock_dt.now.return_value.strftime.return_value = "1430"
monkeypatch.setattr("package.password.datetime", mock_dt)

return {
"base_dir": base_dir,
"snippets_dir": snippets_dir,
"mock_list": mock_list,
"mock_clipboard": mock_clipboard,
"test_snippet": test_snippet
}

def test_display_invalid_password_type(setup_test_env):
with pytest.raises(ValueError):
display("test.txt", "1430", "display")

def test_display_invalid_password_value(setup_test_env):
with pytest.raises(ValueError):
display("test.txt", 1431, "display")

def test_display_file_not_found(setup_test_env):
with patch("builtins.open", mock_open()) as mock_file:
mock_file.side_effect = FileNotFoundError()
display("nonexistent.txt", 1430, "display")

def test_display_action_display(setup_test_env):
env = setup_test_env
mock_file = mock_open(read_data=env["test_snippet"])

with patch("builtins.open", mock_file), \
patch("builtins.print") as mock_print:
display("test.txt", 1430, "display")

mock_print.assert_called_once_with(env["test_snippet"])


def test_display_general_error(setup_test_env):
with patch("builtins.open", mock_open()) as mock_file, \
patch("builtins.print") as mock_print:
mock_file.side_effect = Exception("Test error")
display("test.txt", 1430, "display")

mock_print.assert_called_once_with("Error: Test error")
Loading

0 comments on commit a2ea6b2

Please sign in to comment.