Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 11 additions & 5 deletions commands/add.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,15 @@ def get_tasks_file():

def validate_description(description):
"""Validate task description."""
# NOTE: Validation logic scattered here - should be in utils (refactor bounty)
if not description:
raise ValueError("Description cannot be empty")
if len(description) > 200:
raise ValueError("Description too long (max 200 chars)")
return description.strip()


def add_task(description):
"""Add a new task."""
def add_task(description, json_output=False):
"""Add a new task. Returns task dict if json_output, else prints."""
description = validate_description(description)

tasks_file = get_tasks_file()
Expand All @@ -31,7 +30,14 @@ def add_task(description):
tasks = json.loads(tasks_file.read_text())

task_id = len(tasks) + 1
tasks.append({"id": task_id, "description": description, "done": False})
task = {"id": task_id, "description": description, "done": False}
tasks.append(task)

tasks_file.write_text(json.dumps(tasks, indent=2))
print(f"Added task {task_id}: {description}")

if json_output:
print(json.dumps(task, indent=2))
else:
print(f"Added task {task_id}: {description}")

return task
35 changes: 24 additions & 11 deletions commands/done.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,27 +11,40 @@ def get_tasks_file():

def validate_task_id(tasks, task_id):
"""Validate task ID exists."""
# NOTE: Validation logic scattered here - should be in utils (refactor bounty)
if task_id < 1 or task_id > len(tasks):
raise ValueError(f"Invalid task ID: {task_id}")
return task_id


def mark_done(task_id):
"""Mark a task as complete."""
def mark_done(task_id, json_output=False):
"""Mark a task as complete. Returns task dict if json_output, else prints."""
tasks_file = get_tasks_file()
if not tasks_file.exists():
print("No tasks found!")
return
if json_output:
print(json.dumps({"error": "No tasks found"}))
else:
print("No tasks found!")
return None

tasks = json.loads(tasks_file.read_text())
task_id = validate_task_id(tasks, task_id)

result = None
for task in tasks:
if task["id"] == task_id:
task["done"] = True
tasks_file.write_text(json.dumps(tasks, indent=2))
print(f"Marked task {task_id} as done: {task['description']}")
return

print(f"Task {task_id} not found")
result = task
break

if result:
tasks_file.write_text(json.dumps(tasks, indent=2))
if json_output:
print(json.dumps(result, indent=2))
else:
print(f"Marked task {task_id} as done: {result['description']}")
else:
if json_output:
print(json.dumps({"error": f"Task {task_id} not found"}))
else:
print(f"Task {task_id} not found")

return result
37 changes: 23 additions & 14 deletions commands/list.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,27 +11,36 @@ def get_tasks_file():

def validate_task_file():
"""Validate tasks file exists."""
# NOTE: Validation logic scattered here - should be in utils (refactor bounty)
tasks_file = get_tasks_file()
if not tasks_file.exists():
return []
if tasks_file is None or not tasks_file.exists():
return None
return tasks_file


def list_tasks():
"""List all tasks."""
# NOTE: No --json flag support yet (feature bounty)
def list_tasks(json_output=False):
"""List all tasks. Returns tasks list if json_output, else prints."""
tasks_file = validate_task_file()
if not tasks_file:
print("No tasks yet!")
return
if json_output:
print(json.dumps([]))
else:
print("No tasks yet!")
return []

tasks = json.loads(tasks_file.read_text())

if not tasks:
print("No tasks yet!")
return

for task in tasks:
status = "✓" if task["done"] else " "
print(f"[{status}] {task['id']}. {task['description']}")
if json_output:
print(json.dumps([]))
else:
print("No tasks yet!")
return tasks

if json_output:
print(json.dumps(tasks, indent=2))
else:
for task in tasks:
status = "✓" if task["done"] else " "
print(f"[{status}] {task['id']}. {task['description']}")

return tasks
17 changes: 13 additions & 4 deletions task.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,22 @@
def load_config():
"""Load configuration from file."""
config_path = Path.home() / ".config" / "task-cli" / "config.yaml"
# NOTE: This will crash if config doesn't exist - known bug for bounty testing
if not config_path.exists():
# Create default config with sensible defaults
config_path.parent.mkdir(parents=True, exist_ok=True)
default_config = """# Task CLI Configuration
default_sort: recent
json_output: false
"""
config_path.write_text(default_config)
return default_config
with open(config_path) as f:
return f.read()


def main():
parser = argparse.ArgumentParser(description="Simple task manager")
parser.add_argument("--json", dest="json_output", action="store_true", help="Output in JSON format")
subparsers = parser.add_subparsers(dest="command", help="Command to run")

# Add command
Expand All @@ -36,11 +45,11 @@ def main():
args = parser.parse_args()

if args.command == "add":
add_task(args.description)
result = add_task(args.description, json_output=args.json_output)
elif args.command == "list":
list_tasks()
result = list_tasks(json_output=args.json_output)
elif args.command == "done":
mark_done(args.task_id)
result = mark_done(args.task_id, json_output=args.json_output)
else:
parser.print_help()

Expand Down
158 changes: 157 additions & 1 deletion test_task.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
"""Basic tests for task CLI."""

import json
import sys
import pytest
from io import StringIO
from pathlib import Path
from commands.add import add_task, validate_description
from commands.done import validate_task_id
from commands.done import validate_task_id, mark_done
from commands.list import list_tasks


def test_validate_description():
Expand All @@ -28,3 +31,156 @@ def test_validate_task_id():

with pytest.raises(ValueError):
validate_task_id(tasks, 99)


class TestJSONOutput:
"""Tests for --json flag output."""

def test_add_task_json_output(self, tmp_path, monkeypatch):
"""Test add_task outputs valid JSON when json_output=True."""
tasks_file = tmp_path / "tasks.json"
monkeypatch.setattr("commands.add.get_tasks_file", lambda: tasks_file)

captured = StringIO()
monkeypatch.setattr(sys, "stdout", captured)

result = add_task("Test task", json_output=True)
output = captured.getvalue()

# Verify valid JSON
parsed = json.loads(output)
assert parsed["id"] == 1
assert parsed["description"] == "Test task"
assert parsed["done"] is False
assert result == parsed

def test_list_tasks_json_output(self, tmp_path, monkeypatch):
"""Test list_tasks outputs valid JSON when json_output=True."""
tasks_file = tmp_path / "tasks.json"
tasks_file.write_text(json.dumps([
{"id": 1, "description": "Task 1", "done": False},
{"id": 2, "description": "Task 2", "done": True}
]))
monkeypatch.setattr("commands.list.get_tasks_file", lambda: tasks_file)

captured = StringIO()
monkeypatch.setattr(sys, "stdout", captured)

result = list_tasks(json_output=True)
output = captured.getvalue()

parsed = json.loads(output)
assert len(parsed) == 2
assert parsed[0]["id"] == 1
assert parsed[1]["done"] is True
assert result == parsed

def test_list_tasks_json_empty(self, tmp_path, monkeypatch):
"""Test list_tasks outputs empty JSON array when no tasks."""
monkeypatch.setattr("commands.list.get_tasks_file", lambda: None)

captured = StringIO()
monkeypatch.setattr(sys, "stdout", captured)

result = list_tasks(json_output=True)
output = captured.getvalue()

parsed = json.loads(output)
assert parsed == []
assert result == []

def test_mark_done_json_output(self, tmp_path, monkeypatch):
"""Test mark_done outputs valid JSON when json_output=True."""
tasks_file = tmp_path / "tasks.json"
tasks = [{"id": 1, "description": "Task 1", "done": False}]
tasks_file.write_text(json.dumps(tasks))
monkeypatch.setattr("commands.done.get_tasks_file", lambda: tasks_file)

captured = StringIO()
monkeypatch.setattr(sys, "stdout", captured)

result = mark_done(1, json_output=True)
output = captured.getvalue()

parsed = json.loads(output)
assert parsed["id"] == 1
assert parsed["done"] is True
assert result == parsed

def test_mark_done_json_not_found(self, tmp_path, monkeypatch):
"""Test mark_done outputs error JSON when task not found."""
tasks_file = tmp_path / "tasks.json"
tasks_file.write_text(json.dumps([{"id": 1, "description": "Task 1", "done": False}]))
monkeypatch.setattr("commands.done.get_tasks_file", lambda: tasks_file)

captured = StringIO()
monkeypatch.setattr(sys, "stdout", captured)

result = mark_done(99, json_output=True)
output = captured.getvalue()

parsed = json.loads(output)
assert "error" in parsed
assert result is None


class TestConfigHandling:
"""Tests for config file handling."""

def test_load_config_creates_default(self, tmp_path, monkeypatch):
"""Test load_config creates default config when missing."""
config_dir = tmp_path / ".config" / "task-cli"
config_file = config_dir / "config.yaml"
monkeypatch.setattr("pathlib.Path.home", lambda: tmp_path)

# Config doesn't exist yet
assert not config_file.exists()

from task import load_config
result = load_config()

# Config should now exist
assert config_file.exists()
assert "Task CLI Configuration" in result

def test_load_config_returns_existing(self, tmp_path, monkeypatch):
"""Test load_config returns existing config content."""
config_dir = tmp_path / ".config" / "task-cli"
config_file = config_dir / "config.yaml"
config_dir.mkdir(parents=True)
config_file.write_text("json_output: true\n")
monkeypatch.setattr("pathlib.Path.home", lambda: tmp_path)

from task import load_config
result = load_config()

assert "json_output: true" in result

def test_no_crash_without_config(self, tmp_path, monkeypatch):
"""Test app doesn't crash when config file is missing."""
monkeypatch.setattr("pathlib.Path.home", lambda: tmp_path)

from task import load_config
# Should not raise FileNotFoundError
result = load_config()
assert result is not None
assert len(result) > 0


class TestMarkDoneEdgeCases:
"""Additional mark_done edge case tests."""

def test_mark_done_json_no_tasks(self, tmp_path, monkeypatch):
"""Test mark_done outputs error JSON when no tasks file."""
tasks_file = tmp_path / "nonexistent.json"
monkeypatch.setattr("commands.done.get_tasks_file", lambda: tasks_file)

captured = StringIO()
monkeypatch.setattr(sys, "stdout", captured)

result = mark_done(1, json_output=True)
output = captured.getvalue()

parsed = json.loads(output)
assert "error" in parsed
assert result is None