- --edit splits on commas for tags and for keys already holding a list - --add/--remove change single items, matched by wikilink target, no duplicates - refuse lists with unquoted [[links]] (parsed as nested lists)
537 lines
24 KiB
Python
537 lines
24 KiB
Python
import os
|
|
import unittest
|
|
import yaml
|
|
import shutil
|
|
from pathlib import Path
|
|
from src.onyx import OnyxCLI, cli
|
|
from unittest.mock import patch, MagicMock
|
|
import click
|
|
from click.testing import CliRunner
|
|
from datetime import datetime
|
|
|
|
class TestOnyxCLI(unittest.TestCase):
|
|
def setUp(self):
|
|
# Create temporary test directory and files
|
|
self.test_dir = Path('test_vault')
|
|
self.test_dir.mkdir(exist_ok=True)
|
|
|
|
# Create a temporary config directory
|
|
self.temp_config_dir = Path('temp_config')
|
|
self.temp_config_dir.mkdir(exist_ok=True)
|
|
|
|
# Mock home directory for config
|
|
self.patcher = patch('pathlib.Path.home')
|
|
self.mock_home = self.patcher.start()
|
|
self.mock_home.return_value = Path('temp_config')
|
|
|
|
self.cli = OnyxCLI()
|
|
|
|
# Set up test vault
|
|
self.cli.set_default_vault('test_vault', str(self.test_dir.resolve()))
|
|
|
|
def tearDown(self):
|
|
# Clean up test directories
|
|
self.patcher.stop()
|
|
shutil.rmtree(self.test_dir, ignore_errors=True)
|
|
shutil.rmtree(self.temp_config_dir, ignore_errors=True)
|
|
|
|
def test_set_default_vault(self):
|
|
"""Test setting default vault"""
|
|
self.cli.set_default_vault('new_vault', str(self.test_dir))
|
|
self.assertEqual(self.cli.default_vault, 'new_vault')
|
|
|
|
config = yaml.safe_load(self.cli.config_file.read_text(encoding='utf-8-sig'))
|
|
self.assertEqual(config['default_vault'], 'new_vault')
|
|
self.assertEqual(Path(config['vaults']['new_vault']), self.test_dir.resolve())
|
|
|
|
def test_create_note(self):
|
|
"""Test note creation"""
|
|
# Test basic note creation
|
|
self.cli.create_note('test.md', 'Test content')
|
|
note_path = self.test_dir / 'test.md'
|
|
self.assertTrue(note_path.exists())
|
|
|
|
def test_writes_keep_lf_without_bom(self):
|
|
"""Append and frontmatter edits write LF, no BOM, even on Windows"""
|
|
note_path = self.test_dir / 'lf.md'
|
|
note_path.write_bytes(b'---\nstatus: draft\n---\n# Journal\n')
|
|
|
|
self.cli.create_note('lf.md', '### 10:00 - Entry\nline', append=True)
|
|
self.cli.frontmatter_edit('lf', ('status',), ('done',))
|
|
|
|
data = note_path.read_bytes()
|
|
self.assertNotIn(b'\r', data)
|
|
self.assertFalse(data.startswith(b'\xef\xbb\xbf'))
|
|
self.assertIn(b'status: done', data)
|
|
self.assertTrue(data.endswith(b'# Journal\n\n### 10:00 - Entry\nline'))
|
|
|
|
@unittest.skip("Method export_to_csv not implemented")
|
|
def test_export_to_csv(self):
|
|
"""Test exporting note frontmatter to CSV"""
|
|
# Create a test note with frontmatter
|
|
note_content = """---
|
|
title: Test Note
|
|
tags: [tag1, tag2]
|
|
status: in-progress
|
|
date: 2025-10-28
|
|
custom: value
|
|
---
|
|
Note content"""
|
|
self.cli.create_note('test_note.md', note_content)
|
|
|
|
# Test export with specific columns included
|
|
output_file = self.test_dir / 'output1.csv'
|
|
self.cli.export_to_csv('test_note', str(output_file), include_columns=['title', 'status', 'date'])
|
|
with open(output_file, 'r', encoding='utf-8') as f:
|
|
content = f.read().strip()
|
|
self.assertEqual(content, 'title,status,date\nTest Note,in-progress,2025-10-28')
|
|
|
|
# Test export excluding specific columns
|
|
output_file = self.test_dir / 'output2.csv'
|
|
self.cli.export_to_csv('test_note', str(output_file), exclude_columns=['tags', 'custom'])
|
|
with open(output_file, 'r', encoding='utf-8') as f:
|
|
content = f.read().strip()
|
|
self.assertEqual(content, 'title,status,date\nTest Note,in-progress,2025-10-28')
|
|
|
|
# Test export with both include and exclude (exclude takes precedence)
|
|
output_file = self.test_dir / 'output3.csv'
|
|
self.cli.export_to_csv('test_note', str(output_file),
|
|
include_columns=['title', 'status', 'date', 'custom'],
|
|
exclude_columns=['status'])
|
|
with open(output_file, 'r', encoding='utf-8') as f:
|
|
content = f.read().strip()
|
|
self.assertEqual(content, 'title,date,custom\nTest Note,2025-10-28,value')
|
|
|
|
# Test with non-existent note
|
|
with self.assertRaises(click.UsageError) as context:
|
|
self.cli.export_to_csv('non_existent', 'output.csv')
|
|
self.assertTrue("not found in vault" in str(context.exception))
|
|
|
|
# Test with note without frontmatter
|
|
self.cli.create_note('no_frontmatter.md', 'Just content')
|
|
with self.assertRaises(click.UsageError) as context:
|
|
self.cli.export_to_csv('no_frontmatter', 'output.csv')
|
|
self.assertTrue("No frontmatter found" in str(context.exception))
|
|
|
|
# Test with empty frontmatter
|
|
self.cli.create_note('empty_frontmatter.md', '---\n---\nContent')
|
|
with self.assertRaises(click.UsageError) as context:
|
|
self.cli.export_to_csv('empty_frontmatter', 'output.csv')
|
|
self.assertTrue("Empty frontmatter" in str(context.exception))
|
|
self.assertEqual(note_path.read_text(encoding='utf-8-sig'), 'Test content')
|
|
|
|
# Test note creation with auto-extension
|
|
self.cli.create_note('test2', 'Test content 2')
|
|
self.assertTrue((self.test_dir / 'test2.md').exists())
|
|
|
|
# Test overwrite
|
|
with self.assertRaises(click.UsageError):
|
|
self.cli.create_note('test.md', 'New content')
|
|
self.cli.create_note('test.md', 'New content', overwrite=True)
|
|
self.assertEqual((self.test_dir / 'test.md').read_text(encoding='utf-8-sig'), 'New content')
|
|
|
|
# Test append
|
|
self.cli.create_note('test.md', 'Additional content', append=True)
|
|
self.assertEqual(
|
|
(self.test_dir / 'test.md').read_text(encoding='utf-8-sig'),
|
|
'New content\nAdditional content'
|
|
)
|
|
|
|
def test_frontmatter_operations(self):
|
|
"""Test frontmatter operations"""
|
|
# Create a test note with frontmatter
|
|
initial_content = """---
|
|
title: Test Note
|
|
tags: [test]
|
|
status: draft
|
|
---
|
|
Test content"""
|
|
test_note = 'frontmatter_test.md'
|
|
self.cli.create_note(test_note, initial_content)
|
|
|
|
# Mock click.UsageError for testing
|
|
click_error = click.UsageError
|
|
|
|
# Test that frontmatter operations work correctly
|
|
|
|
# Test frontmatter --edit
|
|
self.cli.frontmatter_edit(test_note, ('tags',), ('test,new',))
|
|
self.cli.frontmatter_edit(test_note, ('status',), ('published',))
|
|
|
|
content = (self.test_dir / test_note).read_text(encoding='utf-8-sig')
|
|
frontmatter = yaml.safe_load(content.split('---')[1])
|
|
self.assertEqual(frontmatter['tags'], ['test', 'new'])
|
|
self.assertEqual(frontmatter['status'], 'published')
|
|
|
|
# Test frontmatter --view
|
|
with patch('click.echo') as mock_echo:
|
|
self.cli.frontmatter_view(test_note, ('tags',))
|
|
mock_echo.assert_called_with("['test', 'new']")
|
|
|
|
# Test frontmatter --view with value check
|
|
with patch('click.echo') as mock_echo:
|
|
self.cli.frontmatter_view(test_note, ('tags',), 'test')
|
|
mock_echo.assert_called_with('tags: true')
|
|
|
|
self.cli.frontmatter_view(test_note, ('tags',), 'nonexistent')
|
|
mock_echo.assert_called_with('tags: false')
|
|
|
|
# Test frontmatter --clear
|
|
self.cli.frontmatter_clear(test_note, ('tags',))
|
|
content = (self.test_dir / test_note).read_text(encoding='utf-8-sig')
|
|
frontmatter = yaml.safe_load(content.split('---')[1])
|
|
self.assertEqual(frontmatter['tags'], [])
|
|
|
|
# Test frontmatter --clear with multiple keys
|
|
self.cli.frontmatter_clear(test_note, ('status,title',))
|
|
content = (self.test_dir / test_note).read_text(encoding='utf-8-sig')
|
|
frontmatter = yaml.safe_load(content.split('---')[1])
|
|
self.assertIsNone(frontmatter['status'])
|
|
self.assertIsNone(frontmatter['title'])
|
|
|
|
# Test frontmatter --delete
|
|
self.cli.frontmatter_delete(test_note, ('tags',))
|
|
content = (self.test_dir / test_note).read_text(encoding='utf-8-sig')
|
|
frontmatter = yaml.safe_load(content.split('---')[1])
|
|
self.assertNotIn('tags', frontmatter)
|
|
|
|
# Test frontmatter --delete with multiple keys
|
|
self.cli.frontmatter_delete(test_note, ('status,title',))
|
|
content = (self.test_dir / test_note).read_text(encoding='utf-8-sig')
|
|
# After deleting all keys, there should be no frontmatter section
|
|
self.assertNotIn('---', content)
|
|
|
|
def test_move_note(self):
|
|
"""Test moving/renaming notes"""
|
|
# Create a test note and another note that links to it
|
|
self.cli.create_note('source.md', 'Test content')
|
|
self.cli.create_note('link.md', 'Link to [[source]]')
|
|
|
|
# Move the note
|
|
self.cli.move_note('source.md', 'folder/dest.md')
|
|
|
|
# Check that the note was moved
|
|
self.assertFalse((self.test_dir / 'source.md').exists())
|
|
self.assertTrue((self.test_dir / 'folder' / 'dest.md').exists())
|
|
|
|
# Check that links were updated
|
|
link_content = (self.test_dir / 'link.md').read_text(encoding='utf-8-sig')
|
|
self.assertIn('[[dest]]', link_content)
|
|
|
|
def test_frontmatter_edit_only_touches_target_keys(self):
|
|
"""Editing keys keeps order, quoting, accents and long lines of the rest"""
|
|
note = self.test_dir / 'meeting.md'
|
|
note.write_text(
|
|
'---\n'
|
|
'client: "[[Symbolitech]]"\n'
|
|
'participants:\n'
|
|
' - "[[Stéphane Charbonneau|Stéphane]]"\n'
|
|
'type: meeting\n'
|
|
'summary: "Une longue phrase de résumé qui dépasse largement quatre-vingts caractères sans être repliée."\n'
|
|
'date: 2026-10-19\n'
|
|
'---\n'
|
|
'# Réunion\n', encoding='utf-8')
|
|
|
|
self.cli.frontmatter_edit('meeting', ('type', 'status', 'parent', 'reviewed'),
|
|
('réunion', 'done', '[[Haro]]', '2026-10-20'))
|
|
self.cli.frontmatter_delete('meeting', ('client',))
|
|
|
|
self.assertEqual(note.read_text(encoding='utf-8'),
|
|
'---\n'
|
|
'participants:\n'
|
|
' - "[[Stéphane Charbonneau|Stéphane]]"\n'
|
|
'type: réunion\n'
|
|
'summary: "Une longue phrase de résumé qui dépasse largement quatre-vingts caractères sans être repliée."\n'
|
|
'date: 2026-10-19\n'
|
|
'status: done\n'
|
|
'parent: "[[Haro]]"\n'
|
|
'reviewed: 2026-10-20\n'
|
|
'---\n'
|
|
'# Réunion\n')
|
|
|
|
def test_frontmatter_edit_adds_frontmatter_to_plain_note(self):
|
|
note = self.test_dir / 'plain.md'
|
|
note.write_text('Corps\n---\nPas un frontmatter\n', encoding='utf-8')
|
|
self.cli.frontmatter_edit('plain', ('tags',), ('a, b',))
|
|
self.assertEqual(note.read_text(encoding='utf-8'),
|
|
'---\ntags:\n - a\n - b\n---\nCorps\n---\nPas un frontmatter\n')
|
|
|
|
MEETING = (
|
|
'---\n'
|
|
'type: meeting\n'
|
|
'participants:\n'
|
|
' - "[[Stéphane Charbonneau|Stéphane]]"\n'
|
|
' - "[[Haro]]"\n'
|
|
'summary: "Résumé : décisions."\n'
|
|
'---\n'
|
|
'Corps\n')
|
|
|
|
def test_frontmatter_edit_keeps_existing_list_type(self):
|
|
"""--edit on a key that is already a list writes a list, not one quoted string"""
|
|
note = self.test_dir / 'm.md'
|
|
note.write_text(self.MEETING, encoding='utf-8')
|
|
self.cli.frontmatter_edit('m', ('participants', 'type'), ('[[Jeffrey]], [[Haro]]', 'réunion, interne'))
|
|
self.assertEqual(note.read_text(encoding='utf-8'), self.MEETING
|
|
.replace(' - "[[Stéphane Charbonneau|Stéphane]]"\n - "[[Haro]]"\n',
|
|
' - "[[Jeffrey]]"\n - "[[Haro]]"\n')
|
|
.replace('type: meeting', 'type: réunion, interne'))
|
|
|
|
def test_frontmatter_add_and_remove_list_items(self):
|
|
"""Items match by link target (alias/case ignored); other items and keys untouched"""
|
|
note = self.test_dir / 'm.md'
|
|
note.write_text(self.MEETING, encoding='utf-8')
|
|
|
|
self.cli.frontmatter_list_items('m', 'participants', ('[[stéphane charbonneau]]', '[[Jeffrey]]', '[[Jeffrey|Jeff]]'))
|
|
self.cli.frontmatter_list_items('m', 'participants', ('[[Haro|H]]',), remove=True)
|
|
self.cli.frontmatter_list_items('m', 'mentioned', ('[[Livre, tome 2]]',))
|
|
self.cli.frontmatter_list_items('m', 'type', ('log',))
|
|
|
|
self.assertEqual(note.read_text(encoding='utf-8'),
|
|
'---\n'
|
|
'type:\n'
|
|
' - meeting\n'
|
|
' - log\n'
|
|
'participants:\n'
|
|
' - "[[Stéphane Charbonneau|Stéphane]]"\n'
|
|
' - "[[Jeffrey]]"\n'
|
|
'summary: "Résumé : décisions."\n'
|
|
'mentioned:\n'
|
|
' - "[[Livre, tome 2]]"\n'
|
|
'---\n'
|
|
'Corps\n')
|
|
|
|
with patch('click.echo') as echo:
|
|
self.cli.frontmatter_list_items('m', 'participants', ('[[Jeffrey|J]]',))
|
|
self.cli.frontmatter_list_items('m', 'absent', ('x',), remove=True)
|
|
self.assertEqual([c.args[0] for c in echo.call_args_list],
|
|
["No change to 'participants' in m", "No change to 'absent' in m"])
|
|
|
|
def test_frontmatter_add_refuses_unquoted_links(self):
|
|
note = self.test_dir / 'bad.md'
|
|
content = '---\nrelated:\n - [[Haro]]\n---\n'
|
|
note.write_text(content, encoding='utf-8')
|
|
with self.assertRaises(click.UsageError):
|
|
self.cli.frontmatter_list_items('bad', 'related', ('[[Plane]]',))
|
|
self.assertEqual(note.read_text(encoding='utf-8'), content)
|
|
|
|
def test_move_rewrites_every_link_form(self):
|
|
"""Aliases, headings, embeds, path links, frontmatter links, regex characters"""
|
|
(self.test_dir / 'films').mkdir()
|
|
(self.test_dir / 'films' / 'Dune (film).md').write_text('Self: [[Dune (film)#Notes]]\n', encoding='utf-8')
|
|
linker = self.test_dir / 'index.md'
|
|
linker.write_text(
|
|
'---\nrelated: "[[Dune (film)|Dune]]"\n---\n'
|
|
'[[Dune (film)]] [[dune (film)#Cast|vu]] ![[Dune (film)#^b1]] '
|
|
'[[films/Dune (film).md]] [[Dune]] [[Other (film)]]\n', encoding='utf-8')
|
|
|
|
with patch('click.echo') as echo:
|
|
self.cli.move_note('films/Dune (film)', 'archives/Dune 2021')
|
|
echo.assert_any_call('Moved films/Dune (film) to archives/Dune 2021 (6 link(s) updated in 2 note(s))')
|
|
|
|
self.assertEqual(linker.read_text(encoding='utf-8'),
|
|
'---\nrelated: "[[Dune 2021|Dune]]"\n---\n'
|
|
'[[Dune 2021]] [[Dune 2021#Cast|vu]] ![[Dune 2021#^b1]] '
|
|
'[[archives/Dune 2021.md]] [[Dune]] [[Other (film)]]\n')
|
|
self.assertEqual((self.test_dir / 'archives' / 'Dune 2021.md').read_text(encoding='utf-8'),
|
|
'Self: [[Dune 2021#Notes]]\n')
|
|
|
|
def test_move_ambiguous_names(self):
|
|
"""Bare links to a non-unique old name stay; a non-unique new name gets a path link"""
|
|
for rel in ('a/Note.md', 'b/Note.md', 'c/Target.md', 'd/Old.md'):
|
|
(self.test_dir / rel).parent.mkdir(exist_ok=True)
|
|
(self.test_dir / rel).write_text('', encoding='utf-8')
|
|
linker = self.test_dir / 'links.md'
|
|
linker.write_text('[[Note]] [[a/Note]] [[Old]]\n', encoding='utf-8')
|
|
|
|
self.cli.move_note('a/Note', 'e/Renamed')
|
|
self.cli.move_note('d/Old', 'f/Target')
|
|
|
|
self.assertEqual(linker.read_text(encoding='utf-8'), '[[Note]] [[e/Renamed]] [[f/Target]]\n')
|
|
|
|
def test_move_refuses_to_overwrite(self):
|
|
self.cli.create_note('one.md', '1')
|
|
self.cli.create_note('two.md', '2')
|
|
with self.assertRaises(click.UsageError):
|
|
self.cli.move_note('one', 'two')
|
|
self.assertEqual((self.test_dir / 'two.md').read_text(encoding='utf-8'), '2')
|
|
self.assertTrue((self.test_dir / 'one.md').exists())
|
|
|
|
def test_periodic_no_open_print_path(self):
|
|
"""--no-open creates without opening Obsidian; --print-path prints only the path"""
|
|
expected = self.test_dir.resolve() / '2025-10-24.md'
|
|
with patch.object(OnyxCLI, 'open_note') as open_note, patch('click.echo') as echo:
|
|
self.cli.daily_note(date='2025-10-24', open_after=False, print_path=True)
|
|
self.cli.daily_note(date='2025-10-24', open_after=False, print_path=True)
|
|
open_note.assert_not_called()
|
|
self.assertEqual([c.args for c in echo.call_args_list], [(str(expected),), (str(expected),)])
|
|
self.assertTrue(expected.exists())
|
|
|
|
def test_daily_note(self):
|
|
"""Test daily note creation"""
|
|
# Mock datetime.now() to return a specific date
|
|
mock_dt = MagicMock()
|
|
mock_dt.strftime.return_value = '2025-10-24'
|
|
with patch('datetime.datetime') as mock_date:
|
|
mock_date.now.return_value = mock_dt
|
|
self.cli.daily_note()
|
|
|
|
daily_note = self.test_dir / '2025-10-24.md'
|
|
self.assertTrue(daily_note.exists())
|
|
# Daily note should be empty since no template is configured
|
|
self.assertEqual(daily_note.read_text(encoding='utf-8-sig'), '')
|
|
|
|
|
|
def test_weekly_note_does_not_inherit_daily_folder(self):
|
|
"""Regression: weekly notes must not silently reuse the daily note's folder/template."""
|
|
obsidian_dir = self.test_dir / '.obsidian'
|
|
obsidian_dir.mkdir(parents=True, exist_ok=True)
|
|
(obsidian_dir / 'daily-notes.json').write_text(
|
|
'{"format": "YYYY-MM-DD", "folder": "periodic/daily", "template": "templates/daily.md"}',
|
|
encoding='utf-8-sig'
|
|
)
|
|
|
|
self.cli.weekly_note(date="2025-11-27")
|
|
|
|
weekly_note = self.test_dir / '2025-W48.md'
|
|
self.assertTrue(weekly_note.exists())
|
|
self.assertFalse((self.test_dir / 'periodic' / 'daily' / '2025-W48.md').exists())
|
|
|
|
def test_periodic_config_edit_and_resolution(self):
|
|
"""onyx's own periodic config wins over plugin/defaults and is used by weekly_note()."""
|
|
template_path = self.test_dir / 'templates' / 'weekly.md'
|
|
template_path.parent.mkdir(parents=True, exist_ok=True)
|
|
template_path.write_text('# Weekly template', encoding='utf-8-sig')
|
|
|
|
self.cli.set_periodic_config(
|
|
'weekly', folder='periodic/weekly', format='YYYY-[W]WW', template='templates/weekly.md'
|
|
)
|
|
|
|
self.cli.weekly_note(date="2025-11-27")
|
|
|
|
weekly_note = self.test_dir / 'periodic' / 'weekly' / '2025-W48.md'
|
|
self.assertTrue(weekly_note.exists())
|
|
self.assertEqual(weekly_note.read_text(encoding='utf-8-sig'), '# Weekly template')
|
|
|
|
config = yaml.safe_load(self.cli.config_file.read_text(encoding='utf-8-sig'))
|
|
saved = config['vaults']['test_vault']['periodic_notes']['weekly']
|
|
self.assertEqual(saved['folder'], 'periodic/weekly')
|
|
self.assertEqual(saved['format'], 'YYYY-[W]WW')
|
|
self.assertEqual(saved['template'], 'templates/weekly.md')
|
|
|
|
def test_periodic_config_view(self):
|
|
"""print_periodic_config reports the resolved settings, not raw config fragments."""
|
|
self.cli.set_periodic_config('monthly', folder='periodic/monthly')
|
|
|
|
with patch('click.echo') as mock_echo:
|
|
self.cli.print_periodic_config('monthly')
|
|
printed = '\n'.join(call.args[0] for call in mock_echo.call_args_list)
|
|
self.assertIn('periodic/monthly', printed)
|
|
self.assertIn('YYYY-MM', printed)
|
|
|
|
def test_quarterly_note_filename(self):
|
|
"""Quarterly notes must resolve the actual quarter number, not a literal 'Q'."""
|
|
self.cli.quarterly_note(date="2025-11-27")
|
|
self.assertTrue((self.test_dir / '2025-Q4.md').exists())
|
|
|
|
@patch('subprocess.run')
|
|
@patch('os.startfile')
|
|
def test_open_note(self, mock_startfile, mock_run):
|
|
"""Test opening notes"""
|
|
# Create a test note
|
|
self.cli.create_note('test.md', 'Test content')
|
|
|
|
# Test opening on different platforms
|
|
with patch('sys.platform', 'win32'):
|
|
self.cli.open_note('test.md')
|
|
mock_startfile.assert_called_with('obsidian://open?vault=test_vault&file=test.md')
|
|
|
|
with patch('sys.platform', 'darwin'):
|
|
self.cli.open_note('test.md')
|
|
mock_run.assert_called_with(['open', 'obsidian://open?vault=test_vault&file=test.md'])
|
|
|
|
with patch('sys.platform', 'linux'):
|
|
self.cli.open_note('test.md')
|
|
mock_run.assert_called_with(['xdg-open', 'obsidian://open?vault=test_vault&file=test.md'])
|
|
|
|
def test_delete_note(self):
|
|
"""Test note deletion"""
|
|
# Create a test note
|
|
self.cli.create_note('test.md', 'Test content')
|
|
self.assertTrue((self.test_dir / 'test.md').exists())
|
|
|
|
# Delete the note
|
|
self.cli.delete_note('test.md')
|
|
self.assertFalse((self.test_dir / 'test.md').exists())
|
|
|
|
# Test deleting non-existent note
|
|
with self.assertRaises(click.UsageError):
|
|
self.cli.delete_note('nonexistent.md')
|
|
|
|
def test_frontmatter_path_resolution(self):
|
|
"""Test frontmatter path resolution with --output-path"""
|
|
# Create a test note with a relative path
|
|
note_content = """---
|
|
path: Projects/my-project
|
|
---
|
|
Test content"""
|
|
test_note = 'path_test.md'
|
|
self.cli.create_note(test_note, note_content)
|
|
|
|
# Setup vault with path prefix
|
|
prefix = str(self.test_dir / 'prefix_root')
|
|
self.cli.set_default_vault('test_vault', str(self.test_dir), path_prefix=prefix)
|
|
|
|
# Test 1: No --output-path (should return raw value)
|
|
with patch('click.echo') as mock_echo:
|
|
self.cli.frontmatter_view(test_note, ('path',), output_path=None)
|
|
mock_echo.assert_called_with('Projects/my-project')
|
|
|
|
# Test 2: --output-path flag (should use config prefix)
|
|
expected_path = str(Path(prefix).resolve() / 'Projects/my-project')
|
|
with patch('click.echo') as mock_echo:
|
|
self.cli.frontmatter_view(test_note, ('path',), output_path=True)
|
|
mock_echo.assert_called_with(expected_path)
|
|
|
|
# Test 3: --output-path with custom value
|
|
custom_prefix = str(self.test_dir / 'custom')
|
|
expected_custom_path = str(Path(custom_prefix) / 'Projects/my-project')
|
|
with patch('click.echo') as mock_echo:
|
|
self.cli.frontmatter_view(test_note, ('path',), output_path=custom_prefix)
|
|
mock_echo.assert_called_with(expected_custom_path)
|
|
|
|
def test_set_default_vault(self):
|
|
"""Test setting default vault"""
|
|
self.cli.set_default_vault('new_vault', str(self.test_dir))
|
|
self.assertEqual(self.cli.default_vault, 'new_vault')
|
|
|
|
config = yaml.safe_load(self.cli.config_file.read_text(encoding='utf-8-sig'))
|
|
self.assertEqual(config['default_vault'], 'new_vault')
|
|
# Check new dict structure
|
|
self.assertEqual(config['vaults']['new_vault']['path'], str(self.test_dir.resolve()))
|
|
|
|
# Test updating with path_prefix
|
|
prefix = "C:\\Users\\test"
|
|
self.cli.set_default_vault('new_vault', str(self.test_dir), path_prefix=prefix)
|
|
|
|
config = yaml.safe_load(self.cli.config_file.read_text(encoding='utf-8-sig'))
|
|
self.assertEqual(config['vaults']['new_vault']['path_prefix'], str(Path(prefix).resolve()))
|
|
|
|
def test_cli_version_flag(self):
|
|
"""onyx --version must work at the root command group (no separate 'version' subcommand)."""
|
|
result = CliRunner().invoke(cli, ['--version'])
|
|
self.assertEqual(result.exit_code, 0)
|
|
self.assertIn('onyx, version', result.output)
|
|
self.assertNotIn('version', [c for c in cli.commands])
|
|
|
|
def test_print_default_shows_path_not_raw_dict(self):
|
|
"""Regression: print_default must print the path string, not the dict, for long-form vault configs."""
|
|
self.cli.set_default_vault('test_vault', str(self.test_dir.resolve()), path_prefix=str(self.test_dir))
|
|
with patch('click.echo') as mock_echo:
|
|
self.cli.print_default()
|
|
printed = '\n'.join(call.args[0] for call in mock_echo.call_args_list)
|
|
self.assertIn(str(self.test_dir.resolve()), printed)
|
|
self.assertNotIn('path_prefix', printed)
|
|
|
|
if __name__ == '__main__':
|
|
unittest.main()
|