Skip to content
Myr

options_test.go

This file

Path

src/options_test.go

604 lines · 17.9 KiB · Go

Last changed by

Allow bare put action in transform outputJunegunn Choibefore adoptionae78a5c

History of this file

Take it

1package fzf23import (4	"fmt"5	"os"6	"testing"78	"github.com/junegunn/fzf/src/tui"9)1011func TestDelimiterRegex(t *testing.T) {12	// Valid regex, but a single character -> string13	delim := delimiterRegexp(".")14	if delim.regex != nil || *delim.str != "." {15		t.Error(delim)16	}17	delim = delimiterRegexp("|")18	if delim.regex != nil || *delim.str != "|" {19		t.Error(delim)20	}21	// Broken regex -> string22	delim = delimiterRegexp("[0-9")23	if delim.regex != nil || *delim.str != "[0-9" {24		t.Error(delim)25	}26	// Valid regex27	delim = delimiterRegexp("[0-9]")28	if delim.regex.String() != "[0-9]" || delim.str != nil {29		t.Error(delim)30	}31	// Tab character32	delim = delimiterRegexp("\t")33	if delim.regex != nil || *delim.str != "\t" {34		t.Error(delim)35	}36	// Tab expression37	delim = delimiterRegexp("\\t")38	if delim.regex != nil || *delim.str != "\t" {39		t.Error(delim)40	}41	// Tabs -> regex42	delim = delimiterRegexp("\t+")43	if delim.regex == nil || delim.str != nil {44		t.Error(delim)45	}46}4748func TestDelimiterRegexString(t *testing.T) {49	delim := delimiterRegexp("*")50	tokens := Tokenize("-*--*---**---", delim)51	if delim.regex != nil ||52		tokens[0].text.ToString() != "-*" ||53		tokens[1].text.ToString() != "--*" ||54		tokens[2].text.ToString() != "---*" ||55		tokens[3].text.ToString() != "*" ||56		tokens[4].text.ToString() != "---" {57		t.Errorf("%s %v %d", delim, tokens, len(tokens))58	}59}6061func TestDelimiterRegexRegex(t *testing.T) {62	delim := delimiterRegexp("--\\*")63	tokens := Tokenize("-*--*---**---", delim)64	if delim.str != nil ||65		tokens[0].text.ToString() != "-*--*" ||66		tokens[1].text.ToString() != "---*" ||67		tokens[2].text.ToString() != "*---" {68		t.Errorf("%s %d", tokens, len(tokens))69	}70}7172func TestDelimiterRegexRegexCaret(t *testing.T) {73	delim := delimiterRegexp(`(^\s*|\s+)`)74	tokens := Tokenize("foo  bar baz", delim)75	if delim.str != nil ||76		len(tokens) != 4 ||77		tokens[0].text.ToString() != "" ||78		tokens[1].text.ToString() != "foo  " ||79		tokens[2].text.ToString() != "bar " ||80		tokens[3].text.ToString() != "baz" {81		t.Errorf("%s %d", tokens, len(tokens))82	}83}8485func TestSplitNth(t *testing.T) {86	{87		ranges, _ := splitNth("..")88		if len(ranges) != 1 ||89			ranges[0].begin != rangeEllipsis ||90			ranges[0].end != rangeEllipsis {91			t.Errorf("%v", ranges)92		}93	}94	{95		ranges, _ := splitNth("..3,1..,2..3,4..-1,-3..-2,..,2,-2,2..-2,1..-1")96		if len(ranges) != 10 ||97			ranges[0].begin != rangeEllipsis || ranges[0].end != 3 ||98			ranges[1].begin != rangeEllipsis || ranges[1].end != rangeEllipsis ||99			ranges[2].begin != 2 || ranges[2].end != 3 ||100			ranges[3].begin != 4 || ranges[3].end != rangeEllipsis ||101			ranges[4].begin != -3 || ranges[4].end != -2 ||102			ranges[5].begin != rangeEllipsis || ranges[5].end != rangeEllipsis ||103			ranges[6].begin != 2 || ranges[6].end != 2 ||104			ranges[7].begin != -2 || ranges[7].end != -2 ||105			ranges[8].begin != 2 || ranges[8].end != -2 ||106			ranges[9].begin != rangeEllipsis || ranges[9].end != rangeEllipsis {107			t.Errorf("%v", ranges)108		}109	}110}111112func TestIrrelevantNth(t *testing.T) {113	index := 0114	{115		opts := defaultOptions()116		words := []string{"--nth", "..", "-x"}117		parseOptions(&index, opts, words)118		postProcessOptions(opts)119		if len(opts.Nth) != 0 {120			t.Errorf("nth should be empty: %v", opts.Nth)121		}122	}123	for _, words := range [][]string{{"--nth", "..,3", "+x"}, {"--nth", "3,1..", "+x"}, {"--nth", "..-1,1", "+x"}} {124		{125			opts := defaultOptions()126			parseOptions(&index, opts, words)127			postProcessOptions(opts)128			if len(opts.Nth) != 0 {129				t.Errorf("nth should be empty: %v", opts.Nth)130			}131		}132		{133			opts := defaultOptions()134			words = append(words, "-x")135			parseOptions(&index, opts, words)136			postProcessOptions(opts)137			if len(opts.Nth) != 2 {138				t.Errorf("nth should not be empty: %v", opts.Nth)139			}140		}141	}142}143144func TestParseKeys(t *testing.T) {145	pairs, _, _ := parseKeyChords("ctrl-z,alt-z,f2,@,Alt-a,!,ctrl-G,J,g,ctrl-alt-a,ALT-enter,alt-SPACE", "")146	checkEvent := func(e tui.Event, s string) {147		if pairs[e] != s {148			t.Errorf("%s != %s", pairs[e], s)149		}150	}151	check := func(et tui.EventType, s string) {152		checkEvent(et.AsEvent(), s)153	}154	if len(pairs) != 12 {155		t.Error(12)156	}157	check(tui.CtrlZ, "ctrl-z")158	check(tui.F2, "f2")159	check(tui.CtrlG, "ctrl-G")160	checkEvent(tui.AltKey('z'), "alt-z")161	checkEvent(tui.Key('@'), "@")162	checkEvent(tui.AltKey('a'), "Alt-a")163	checkEvent(tui.Key('!'), "!")164	checkEvent(tui.Key('J'), "J")165	checkEvent(tui.Key('g'), "g")166	checkEvent(tui.CtrlAltKey('a'), "ctrl-alt-a")167	checkEvent(tui.CtrlAltKey('m'), "ALT-enter")168	checkEvent(tui.AltKey(' '), "alt-SPACE")169170	// Synonyms171	pairs, _, _ = parseKeyChords("enter,Return,space,tab,btab,esc,up,down,left,right", "")172	if len(pairs) != 9 {173		t.Error(9)174	}175	check(tui.Enter, "Return")176	checkEvent(tui.Key(' '), "space")177	check(tui.Tab, "tab")178	check(tui.ShiftTab, "btab")179	check(tui.Esc, "esc")180	check(tui.Up, "up")181	check(tui.Down, "down")182	check(tui.Left, "left")183	check(tui.Right, "right")184185	pairs, _, _ = parseKeyChords("Tab,Ctrl-I,PgUp,page-up,pgdn,Page-Down,Home,End,Alt-BS,Alt-BSpace,shift-left,shift-right,btab,shift-tab,return,Enter,bspace", "")186	if len(pairs) != 11 {187		t.Error(11)188	}189	check(tui.Tab, "Ctrl-I")190	check(tui.PageUp, "page-up")191	check(tui.PageDown, "Page-Down")192	check(tui.Home, "Home")193	check(tui.End, "End")194	check(tui.AltBackspace, "Alt-BSpace")195	check(tui.ShiftLeft, "shift-left")196	check(tui.ShiftRight, "shift-right")197	check(tui.ShiftTab, "shift-tab")198	check(tui.Enter, "Enter")199	check(tui.Backspace, "bspace")200}201202func TestParseKeysWithComma(t *testing.T) {203	checkN := func(a int, b int) {204		if a != b {205			t.Errorf("%d != %d", a, b)206		}207	}208	check := func(pairs map[tui.Event]string, e tui.Event, s string) {209		if pairs[e] != s {210			t.Errorf("%s != %s", pairs[e], s)211		}212	}213214	pairs, _, _ := parseKeyChords(",", "")215	checkN(len(pairs), 1)216	check(pairs, tui.Key(','), ",")217218	pairs, _, _ = parseKeyChords(",,a,b", "")219	checkN(len(pairs), 3)220	check(pairs, tui.Key('a'), "a")221	check(pairs, tui.Key('b'), "b")222	check(pairs, tui.Key(','), ",")223224	pairs, _, _ = parseKeyChords("a,b,,", "")225	checkN(len(pairs), 3)226	check(pairs, tui.Key('a'), "a")227	check(pairs, tui.Key('b'), "b")228	check(pairs, tui.Key(','), ",")229230	pairs, _, _ = parseKeyChords("a,,,b", "")231	checkN(len(pairs), 3)232	check(pairs, tui.Key('a'), "a")233	check(pairs, tui.Key('b'), "b")234	check(pairs, tui.Key(','), ",")235236	pairs, _, _ = parseKeyChords("a,,,b,c", "")237	checkN(len(pairs), 4)238	check(pairs, tui.Key('a'), "a")239	check(pairs, tui.Key('b'), "b")240	check(pairs, tui.Key('c'), "c")241	check(pairs, tui.Key(','), ",")242243	pairs, _, _ = parseKeyChords(",,,", "")244	checkN(len(pairs), 1)245	check(pairs, tui.Key(','), ",")246247	pairs, _, _ = parseKeyChords(",ALT-,,", "")248	checkN(len(pairs), 1)249	check(pairs, tui.AltKey(','), "ALT-,")250}251252func TestBind(t *testing.T) {253	keymap := defaultKeymap()254	check := func(event tui.Event, arg1 string, types ...actionType) {255		if len(keymap[event]) != len(types) {256			t.Errorf("invalid number of actions for %v (%d != %d)",257				event, len(types), len(keymap[event]))258			return259		}260		for idx, action := range keymap[event] {261			if types[idx] != action.t {262				t.Errorf("invalid action type (%d != %d)", types[idx], action.t)263			}264		}265		if len(arg1) > 0 && keymap[event][0].a != arg1 {266			t.Errorf("invalid action argument: (%s != %s)", arg1, keymap[event][0].a)267		}268	}269	check(tui.CtrlA.AsEvent(), "", actBeginningOfLine)270	parseKeymap(keymap,271		"ctrl-a:kill-line,ctrl-b:toggle-sort+up+down,c:page-up,alt-z:page-down,"+272			"f1:execute(ls {+})+abort+execute(echo \n{+})+select-all,f2:execute/echo {}, {}, {}/,f3:execute[echo '({})'],f4:execute;less {};,"+273			"alt-a:execute-Multi@echo (,),[,],/,:,;,%,{}@,alt-b:execute;echo (,),[,],/,:,@,%,{};,"+274			"x:Execute(foo+bar),X:execute/bar+baz/"+275			",f1:+first,f1:+top"+276			",,:abort,::accept,+:execute:++\nfoobar,Y:execute(baz)+up")277	check(tui.CtrlA.AsEvent(), "", actKillLine)278	check(tui.CtrlB.AsEvent(), "", actToggleSort, actUp, actDown)279	check(tui.Key('c'), "", actPageUp)280	check(tui.Key(','), "", actAbort)281	check(tui.Key(':'), "", actAccept)282	check(tui.AltKey('z'), "", actPageDown)283	check(tui.F1.AsEvent(), "ls {+}", actExecute, actAbort, actExecute, actSelectAll, actFirst, actFirst)284	check(tui.F2.AsEvent(), "echo {}, {}, {}", actExecute)285	check(tui.F3.AsEvent(), "echo '({})'", actExecute)286	check(tui.F4.AsEvent(), "less {}", actExecute)287	check(tui.Key('x'), "foo+bar", actExecute)288	check(tui.Key('X'), "bar+baz", actExecute)289	check(tui.AltKey('a'), "echo (,),[,],/,:,;,%,{}", actExecuteMulti)290	check(tui.AltKey('b'), "echo (,),[,],/,:,@,%,{}", actExecute)291	check(tui.Key('+'), "++\nfoobar,Y:execute(baz)+up", actExecute)292293	for idx, char := range []rune{'~', '!', '@', '#', '$', '%', '^', '&', '*', '|', ';', '/'} {294		parseKeymap(keymap, fmt.Sprintf("%d:execute%cfoobar%c", idx%10, char, char))295		check(tui.Key([]rune(fmt.Sprintf("%d", idx%10))[0]), "foobar", actExecute)296	}297298	parseKeymap(keymap, "f1:abort")299	check(tui.F1.AsEvent(), "", actAbort)300}301302func TestParseEveryEvent(t *testing.T) {303	pairs, _, err := parseKeyChords("every(2),every(0.5)", "")304	if err != nil {305		t.Fatalf("unexpected error: %v", err)306	}307	if len(pairs) != 2 {308		t.Errorf("expected 2 distinct every events, got %d", len(pairs))309	}310	if pairs[(tui.Event{Type: tui.Every, Char: 2000})] != "every(2)" {311		t.Errorf("every(2) not registered")312	}313	if pairs[(tui.Event{Type: tui.Every, Char: 500})] != "every(0.5)" {314		t.Errorf("every(0.5) not registered")315	}316317	// Floor at 0.01s -> 10ms318	pairs, _, err = parseKeyChords("every(0.001)", "")319	if err != nil {320		t.Fatalf("unexpected error: %v", err)321	}322	if pairs[(tui.Event{Type: tui.Every, Char: 10})] != "every(0.001)" {323		t.Errorf("every(0.001) should floor to 10ms")324	}325326	// Reject zero, negatives, and overflow (>= 2^31 ms = ~24.85 days)327	for _, bad := range []string{"every(0)", "every(-1)", "every(abc)", "every()", "every(2147484)"} {328		if _, _, err := parseKeyChords(bad, ""); err == nil {329			t.Errorf("%s should be rejected", bad)330		}331	}332333}334335func TestColorSpec(t *testing.T) {336	var base *tui.ColorTheme337	theme := tui.Dark256338	base, dark, _ := parseTheme(theme, "dark")339	if *dark != *base {340		t.Errorf("incorrect base theme returned")341	}342	if *dark != *theme {343		t.Errorf("colors should be equivalent")344	}345	if dark == theme {346		t.Errorf("point should not be equivalent")347	}348349	base, light, _ := parseTheme(theme, "dark,light")350	if *light != *base {351		t.Errorf("incorrect base theme returned")352	}353	if *light == *theme {354		t.Errorf("should not be equivalent")355	}356	if *light != *tui.Light256 {357		t.Errorf("colors should be equivalent")358	}359	if light == theme {360		t.Errorf("point should not be equivalent")361	}362363	_, customized, _ := parseTheme(theme, "fg:231,bg:232")364	if customized.Fg.Color != 231 || customized.Bg.Color != 232 {365		t.Errorf("color not customized")366	}367	if *tui.Dark256 == *customized {368		t.Errorf("colors should not be equivalent")369	}370	customized.Fg = tui.Dark256.Fg371	customized.Bg = tui.Dark256.Bg372	if *tui.Dark256 != *customized {373		t.Errorf("colors should now be equivalent: %v, %v", tui.Dark256, customized)374	}375376	_, customized, _ = parseTheme(theme, "fg:231,dark   bg:232")377	if customized.Fg != tui.Dark256.Fg || customized.Bg == tui.Dark256.Bg {378		t.Errorf("color not customized")379	}380}381382func TestDefaultCtrlNP(t *testing.T) {383	index := 0384	check := func(words []string, et tui.EventType, expected actionType) {385		e := et.AsEvent()386		opts := defaultOptions()387		parseOptions(&index, opts, words)388		postProcessOptions(opts)389		if opts.Keymap[e][0].t != expected {390			t.Error()391		}392	}393	check([]string{}, tui.CtrlN, actDownMatch)394	check([]string{}, tui.CtrlP, actUpMatch)395396	check([]string{"--bind=ctrl-n:accept"}, tui.CtrlN, actAccept)397	check([]string{"--bind=ctrl-p:accept"}, tui.CtrlP, actAccept)398399	f, _ := os.CreateTemp("", "fzf-history")400	f.Close()401	hist := "--history=" + f.Name()402	check([]string{hist}, tui.CtrlN, actNextHistory)403	check([]string{hist}, tui.CtrlP, actPrevHistory)404405	check([]string{hist, "--bind=ctrl-n:accept"}, tui.CtrlN, actAccept)406	check([]string{hist, "--bind=ctrl-n:accept"}, tui.CtrlP, actPrevHistory)407408	check([]string{hist, "--bind=ctrl-p:accept"}, tui.CtrlN, actNextHistory)409	check([]string{hist, "--bind=ctrl-p:accept"}, tui.CtrlP, actAccept)410}411412func optsFor(words ...string) *Options {413	index := 0414	opts := defaultOptions()415	parseOptions(&index, opts, words)416	postProcessOptions(opts)417	return opts418}419420func TestToggle(t *testing.T) {421	opts := optsFor()422	if opts.ToggleSort {423		t.Error()424	}425426	opts = optsFor("--bind=a:toggle-sort")427	if !opts.ToggleSort {428		t.Error()429	}430431	opts = optsFor("--bind=a:toggle-sort", "--bind=a:up")432	if opts.ToggleSort {433		t.Error()434	}435}436437func TestPreviewOpts(t *testing.T) {438	opts := optsFor()439	if !(opts.Preview.command == "" &&440		opts.Preview.hidden == false &&441		opts.Preview.wrap == false &&442		opts.Preview.position == posRight &&443		opts.Preview.size.percent == true &&444		opts.Preview.size.size == 50) {445		t.Error()446	}447	opts = optsFor("--preview", "cat {}", "--preview-window=left:15,hidden,wrap:+{1}-/2")448	if !(opts.Preview.command == "cat {}" &&449		opts.Preview.hidden == true &&450		opts.Preview.wrap == true &&451		opts.Preview.position == posLeft &&452		opts.Preview.scroll == "+{1}-/2" &&453		opts.Preview.size.percent == false &&454		opts.Preview.size.size == 15) {455		t.Error(opts.Preview)456	}457	opts = optsFor("--preview-window=up,15,wrap,hidden,+{1}+3-1-2/2", "--preview-window=down", "--preview-window=cycle")458	if !(opts.Preview.command == "" &&459		opts.Preview.hidden == true &&460		opts.Preview.wrap == true &&461		opts.Preview.cycle == true &&462		opts.Preview.position == posDown &&463		opts.Preview.scroll == "+{1}+3-1-2/2" &&464		opts.Preview.size.percent == false &&465		opts.Preview.size.size == 15) {466		t.Error(opts.Preview.size.size)467	}468	opts = optsFor("--preview-window=up:15:wrap:hidden")469	if !(opts.Preview.command == "" &&470		opts.Preview.hidden == true &&471		opts.Preview.wrap == true &&472		opts.Preview.position == posUp &&473		opts.Preview.size.percent == false &&474		opts.Preview.size.size == 15) {475		t.Error(opts.Preview)476	}477	opts = optsFor("--preview=foo", "--preview-window=up", "--preview-window=default:70%")478	if !(opts.Preview.command == "foo" &&479		opts.Preview.position == posRight &&480		opts.Preview.size.percent == true &&481		opts.Preview.size.size == 70) {482		t.Error(opts.Preview)483	}484485	// wrap-word tests486	opts = optsFor("--preview-window=wrap-word")487	if !(opts.Preview.wrap == true && opts.Preview.wrapWord == true) {488		t.Errorf("wrap-word: wrap=%v, wrapWord=%v", opts.Preview.wrap, opts.Preview.wrapWord)489	}490	opts = optsFor("--preview-window=wrap-word,nowrap")491	if !(opts.Preview.wrap == false && opts.Preview.wrapWord == false) {492		t.Errorf("wrap-word,nowrap: wrap=%v, wrapWord=%v", opts.Preview.wrap, opts.Preview.wrapWord)493	}494	opts = optsFor("--preview-window=wrap-word,wrap")495	if !(opts.Preview.wrap == true && opts.Preview.wrapWord == false) {496		t.Errorf("wrap-word,wrap: wrap=%v, wrapWord=%v", opts.Preview.wrap, opts.Preview.wrapWord)497	}498}499500func TestPreviewWrapSign(t *testing.T) {501	// Default: no preview wrap sign override502	opts := optsFor()503	if opts.PreviewWrapSign != nil {504		t.Errorf("expected nil PreviewWrapSign, got %v", *opts.PreviewWrapSign)505	}506507	// --preview-wrap-sign sets PreviewWrapSign508	opts = optsFor("--preview-wrap-sign", ">> ")509	if opts.PreviewWrapSign == nil || *opts.PreviewWrapSign != ">> " {510		t.Errorf("expected '>> ', got %v", opts.PreviewWrapSign)511	}512513	// --preview-wrap-sign is independent of --wrap-sign514	opts = optsFor("--wrap-sign", "| ", "--preview-wrap-sign", ">> ")515	if opts.WrapSign == nil || *opts.WrapSign != "| " {516		t.Errorf("expected WrapSign '| ', got %v", opts.WrapSign)517	}518	if opts.PreviewWrapSign == nil || *opts.PreviewWrapSign != ">> " {519		t.Errorf("expected PreviewWrapSign '>> ', got %v", opts.PreviewWrapSign)520	}521522	// --preview-wrap-sign without --wrap-sign523	opts = optsFor("--preview-wrap-sign", "→ ")524	if opts.WrapSign != nil {525		t.Errorf("expected nil WrapSign, got %v", *opts.WrapSign)526	}527	if opts.PreviewWrapSign == nil || *opts.PreviewWrapSign != "→ " {528		t.Errorf("expected PreviewWrapSign '→ ', got %v", opts.PreviewWrapSign)529	}530531	// Last --preview-wrap-sign wins532	opts = optsFor("--preview-wrap-sign", "A ", "--preview-wrap-sign", "B ")533	if opts.PreviewWrapSign == nil || *opts.PreviewWrapSign != "B " {534		t.Errorf("expected PreviewWrapSign 'B ', got %v", opts.PreviewWrapSign)535	}536537	// Empty string is allowed538	opts = optsFor("--preview-wrap-sign", "")539	if opts.PreviewWrapSign == nil || *opts.PreviewWrapSign != "" {540		t.Errorf("expected empty PreviewWrapSign, got %v", opts.PreviewWrapSign)541	}542}543544func TestAdditiveExpect(t *testing.T) {545	opts := optsFor("--expect=a", "--expect", "b", "--expect=c")546	if len(opts.Expect) != 3 {547		t.Error(opts.Expect)548	}549}550551func TestValidateSign(t *testing.T) {552	testCases := []struct {553		inputSign string554		isValid   bool555	}{556		{"> ", true},557		{"아", true},558		{"😀", true},559		{">>>", false},560	}561562	for _, testCase := range testCases {563		err := validateSign(testCase.inputSign, "", 2)564		if testCase.isValid && err != nil {565			t.Errorf("Input sign `%s` caused error", testCase.inputSign)566		}567568		if !testCase.isValid && err == nil {569			t.Errorf("Input sign `%s` did not cause error", testCase.inputSign)570		}571	}572}573574func TestParseSingleActionList(t *testing.T) {575	actions, _ := parseSingleActionList("Execute@foo+bar,baz@+up+up+reload:down+down", false)576	if len(actions) != 4 {577		t.Errorf("Invalid number of actions parsed:%d", len(actions))578	}579	if actions[0].t != actExecute || actions[0].a != "foo+bar,baz" {580		t.Errorf("Invalid action parsed: %v", actions[0])581	}582	if actions[1].t != actUp || actions[2].t != actUp {583		t.Errorf("Invalid action parsed: %v / %v", actions[1], actions[2])584	}585	if actions[3].t != actReload || actions[3].a != "down+down" {586		t.Errorf("Invalid action parsed: %v", actions[3])587	}588}589590func TestParseSingleActionListError(t *testing.T) {591	_, err := parseSingleActionList("change-query(foobar)baz", false)592	if err == nil {593		t.Errorf("Failed to detect error")594	}595}596597func TestMaskActionContents(t *testing.T) {598	original := ":execute((f)(o)(o)(b)(a)(r))+change-query@qu@ry@+up,x:reload:hello:world"599	expected := ":execute                    +change-query       +up,x:reload            "600	masked := maskActionContents(original)601	if masked != expected {602		t.Errorf("Not masked: %s", masked)603	}604}