package pythonlang import ( "fmt" "os" "strings" "testing" "rickub.com/turbo-editors/turbo-core/settings" "rickub.com/turbo-editors/turbo-core/snippets" "rickub.com/turbo-editors/turbo-core/syntax" "rickub.com/turbo-editors/turbo-core/tools" ) // The starter files Turbo Python writes are the one part of a project's // .turbo-python directory that is about Python, so this is where what is *in* // them is checked. That the file written is the profile's template at all is // turbo-core's test. // noUserSnippets points the user's own snippets at an empty directory, so a // test never reads whoever is running it. func noUserSnippets(t *testing.T) { t.Helper() t.Setenv(Profile().SnippetDirEnvVar(), t.TempDir()) } // createTools writes a project's tools file and returns the project directory. func createTools(t *testing.T) string { t.Helper() dir := t.TempDir() if _, err := tools.Create(Profile(), dir); err != nil { t.Fatalf("tools.Create() error = %v", err) } return dir } // createSnippets writes a project's snippets file and returns the directory. func createSnippets(t *testing.T) string { t.Helper() noUserSnippets(t) dir := t.TempDir() if _, err := snippets.Create(Profile(), dir); err != nil { t.Fatalf("snippets.Create() error = %v", err) } return dir } // createSettings writes a project's settings file and returns the directory. func createSettings(t *testing.T) string { t.Helper() dir := t.TempDir() if _, err := settings.Create(Profile(), dir, "turbo-classic"); err != nil { t.Fatalf("settings.Create() error = %v", err) } return dir } // loadTools reads a project's tools, failing the test if it cannot. func loadTools(t *testing.T, dir string) tools.List { t.Helper() list, err := tools.Load(Profile(), dir) if err != nil { t.Fatalf("tools.Load(%q) error = %v", dir, err) } return list } // loadSnippets reads a project's snippets, failing the test if it cannot. func loadSnippets(t *testing.T, dir string) snippets.List { t.Helper() list, err := snippets.Load(Profile(), dir) if err != nil { t.Fatalf("snippets.Load(%q) error = %v", dir, err) } return list } // readFile returns a file's contents. func readFile(t *testing.T, path string) string { t.Helper() data, err := os.ReadFile(path) if err != nil { t.Fatalf("reading %s: %v", path, err) } return string(data) } // plain strips the tilde hot-key markers from a label. func plain(label string) string { return strings.ReplaceAll(label, "~", "") } // hotKey returns the character between the tildes, or 0 when there is none. func hotKey(label string) rune { first := strings.IndexByte(label, '~') if first < 0 || first+1 >= len(label) { return 0 } return rune(label[first+1]) } // --- the tools file --------------------------------------------------------- func TestTheCreatedToolsFileHoldsTheSixCommandsAProjectRuns(t *testing.T) { // These are what a Python project runs on itself, and they are the reason // the file exists at all. Everything goes through uv, so none of them needs // an environment to have been activated first. byName := map[string]string{} for _, tool := range loadTools(t, createTools(t)).In("Python") { byName[plain(tool.Name)] = tool.Command } want := map[string]string{ "Environment": "uv venv {{directory, usually .venv}}", "Sync": "uv sync", "Format": "uv run ruff format .", "Lint": "uv run ruff check .", "Test": "uv run pytest", "Run": "uv run {{script}}", } for name, command := range want { if got := byName[name]; got != command { t.Errorf("%s runs %q, want %q", name, got, command) } } if len(byName) != len(want) { t.Errorf("the Python menu holds %d tools, want %d: %v", len(byName), len(want), byName) } } // Creating the environment is the step in Python that has to happen before any // of the others can, and the one a newcomer to a project most often has not // done — so it is the first item in the menu rather than the last. func TestCreatingTheEnvironmentIsTheFirstToolInTheMenu(t *testing.T) { python := loadTools(t, createTools(t)).In("Python") if len(python) == 0 { t.Fatal("the Python menu is empty") } if got := plain(python[0].Name); got != "Environment" { t.Errorf("the first tool in the menu is %q, want %q", got, "Environment") } } // The directory is asked for rather than fixed: .venv is the usual answer and // not the only one, and a tool that asks is also the file's live demonstration // that asking is possible. func TestTheEnvironmentToolAsksWhereToPutIt(t *testing.T) { for _, tool := range loadTools(t, createTools(t)).Tools() { if plain(tool.Name) != "Environment" { continue } asked := tool.Placeholders() if len(asked) != 1 { t.Fatalf("Environment asks for %d values, want 1: %v", len(asked), asked) } if !strings.Contains(asked[0].Label, ".venv") { t.Errorf("it asks for %q, which never mentions .venv", asked[0].Label) } if asked[0].Raw { t.Errorf("it asks for %q unquoted; a directory with a space in it would become two arguments", asked[0].Label) } return } t.Fatal("there is no Environment tool") } func TestOnlyTheTwoToolsThatNeedAValueAskForOne(t *testing.T) { // Every other command is complete as it stands, and a box in front of a // command that has nothing to ask is a keystroke for nothing. asking := map[string]bool{"Environment": true, "Run": true} for _, tool := range loadTools(t, createTools(t)).Tools() { name := plain(tool.Name) if got := len(tool.Placeholders()) > 0; got != asking[name] { t.Errorf("%s asks for a value: %t, want %t (%q)", name, got, asking[name], tool.Command) } } } func TestTheCreatedToolsCarryHotKeysUniqueWithinTheirMenu(t *testing.T) { // Six items in a menu are worth reaching with one keystroke each. Two menus // may each have an E, which is why the check is per menu. list := loadTools(t, createTools(t)) for _, menu := range list.MenuNames() { seen := map[rune]string{} for _, tool := range list.In(menu) { key := hotKey(tool.Name) if key == 0 { t.Errorf("%q in the %s menu has no hot key", tool.Name, menu) continue } if other, clash := seen[key]; clash { t.Errorf("%q and %q in the %s menu both answer to %c", other, tool.Name, menu, key) } seen[key] = tool.Name } } } func TestTheCreatedToolsFileNamesAnOutputForEveryTool(t *testing.T) { // The key is the interesting part of the format, and a file where it only // appears once is a file where nobody notices it exists. for _, tool := range loadTools(t, createTools(t)).Tools() { if tool.Output == "" { t.Errorf("%q leaves its output to the default rather than saying it", tool.Name) } } } func TestRunIsTheOneToolchainCommandInATerminal(t *testing.T) { // A Python script usually reads the keyboard, runs long, or both, and a // popup can answer neither. The Echo example is in a terminal too, but it // is in a menu of its own and is there to demonstrate the menu key. for _, tool := range loadTools(t, createTools(t)).In("Python") { want := tools.OutputPopup if plain(tool.Name) == "Run" { want = tools.OutputTerminal } if got := tool.Where(); got != want { t.Errorf("%s goes to %q, want %q", plain(tool.Name), got, want) } } } func TestTheCreatedToolsFileExplainsItself(t *testing.T) { contents := readFile(t, tools.Path(Profile(), createTools(t))) for _, want := range []string{"[[tool]]", "sh -c", "hot key", "popup", "terminal", "editor"} { if !strings.Contains(contents, want) { t.Errorf("the created file never mentions %q:\n%s", want, contents) } } } func TestTheCreatedToolsFileNamesThePythonMenuAndNoOtherEditorsMenu(t *testing.T) { // The comments explain which menu a tool lands in by naming it. Naming the // menu of the editor this one was adapted from is the copy-and-paste // mistake this catches, and it is invisible to every other test. contents := readFile(t, tools.Path(Profile(), createTools(t))) if !strings.Contains(contents, "Python menu") { t.Errorf("the created file never names the Python menu:\n%s", contents) } for _, other := range []string{"Go menu", "Rust menu", "turbo-go", "turbo-rust", "cargo"} { if strings.Contains(contents, other) { t.Errorf("the created file still talks about %q:\n%s", other, contents) } } } func TestTheCreatedToolsFileShowsHowToUseAnotherMenu(t *testing.T) { contents := readFile(t, tools.Path(Profile(), createTools(t))) for _, want := range []string{"menu says which menu", `menu = "Tools"`} { if !strings.Contains(contents, want) { t.Errorf("the created file never shows %q:\n%s", want, contents) } } } func TestTheCreatedToolsFileExplainsHowToAskForAValue(t *testing.T) { // A parameterised tool is only discoverable if the file people get says the // syntax exists. The double-brace warning is here too, because somebody // reading this file may well have an awk one-liner in mind. contents := readFile(t, tools.Path(Profile(), createTools(t))) for _, want := range []string{ "{{label}}", "uv add {{package}}", "{{extra flags...}}", "Double braces, not single", } { if !strings.Contains(contents, want) { t.Errorf("the created file never mentions %q:\n%s", want, contents) } } } // --- the snippets file ------------------------------------------------------ func TestTheCreatedSnippetsFileHoldsUsablePythonSnippets(t *testing.T) { groups := loadSnippets(t, createSnippets(t)).Groups(string(Language)) if len(groups) == 0 { t.Fatal("the created file offers nothing at all in a Python file") } for _, group := range groups { for _, snippet := range group.Snippets { if snippet.Name == "" || snippet.Body == "" { t.Errorf("the created file holds an unusable snippet %+v", snippet) } } } } func TestTheCreatedSnippetsIndentWithFourSpacesTheWayPEP8Does(t *testing.T) { // A tab inserted into a file indented with spaces is an indentation error // in Python, not a formatting quibble: the file stops running. for _, group := range loadSnippets(t, createSnippets(t)).Groups(string(Language)) { for _, snippet := range group.Snippets { if strings.Contains(snippet.Body, "\t") { t.Errorf("%q indents with a tab:\n%q", snippet.Name, snippet.Body) } for _, line := range strings.Split(snippet.Body, "\n") { indent := len(line) - len(strings.TrimLeft(line, " ")) if indent%4 != 0 { t.Errorf("%q has a line indented by %d spaces:\n%q", snippet.Name, indent, line) } } } } } // Every snippet must be Python that runs, not Python that looks right — the // scanner is the nearest thing to a parser this repository has, and a snippet // whose whole body comes out as one colour is a snippet with an unclosed // string in it. func TestEverySnippetBodyColoursAsMoreThanOneThing(t *testing.T) { for _, group := range loadSnippets(t, createSnippets(t)).Groups(string(Language)) { for _, snippet := range group.Snippets { classes := map[syntax.Class]bool{} for _, line := range Highlight(snippet.Body) { for _, span := range line { classes[span.Class] = true } } if len(classes) < 2 { t.Errorf("%q colours as %d classes:\n%s", snippet.Name, len(classes), snippet.Body) } } } } func TestTheCreatedSnippetsFileExplainsItself(t *testing.T) { contents := readFile(t, snippets.ProjectPath(Profile(), createSnippets(t))) for _, want := range []string{"[[snippet]]", "languages", "group", "General", snippets.UserPath(Profile())} { if !strings.Contains(contents, want) { t.Errorf("the created file never mentions %q:\n%s", want, contents) } } } func TestTheCreatedSnippetsFileListsEveryLanguageTheEditorKnows(t *testing.T) { // The comment is where a user finds out what they may write in a languages // key. One that omits a language the editor colours sends them looking for // a feature that is already there. Iterating the registry rather than a // list is what stops the comment falling behind it, as turbo-rust's did // when turbo-core learnt YAML, XML and Dockerfiles. Register() contents := readFile(t, snippets.ProjectPath(Profile(), createSnippets(t))) for _, language := range syntax.Registered() { if !strings.Contains(contents, string(language)) { t.Errorf("the created file never mentions the %q language:\n%s", language, contents) } } } // --- the settings file ------------------------------------------------------ func TestTheCreatedSettingsFileExplainsItself(t *testing.T) { contents := readFile(t, settings.Path(Profile(), createSettings(t))) for _, want := range []string{"theme", "autosave", "autosave_delay", "-list-themes"} { if !strings.Contains(contents, want) { t.Errorf("the created file never mentions %q:\n%s", want, contents) } } } func TestTheCreatedSettingsFileTurnsAutosaveOn(t *testing.T) { // A project that has gone to the trouble of creating a settings file has // said what it wants. The file is the visible, editable place to say // otherwise, which is why this default lives here and not in the library. project := createSettings(t) loaded, err := settings.Load(Profile(), project) if err != nil { t.Fatalf("settings.Load() error = %v", err) } if !loaded.Autosave { t.Errorf("the created settings file leaves autosave off:\n%s", readFile(t, settings.Path(Profile(), project))) } if loaded.AutosaveDelay != settings.DefaultAutosaveDelay { t.Errorf("AutosaveDelay = %v, want the library default %v", loaded.AutosaveDelay, settings.DefaultAutosaveDelay) } } func TestAProjectWithNoSettingsFileStillDoesNotAutosave(t *testing.T) { // The other half of the decision. Turning autosave on for a project that // never opted in would mean the editor writing to disk in any directory it // is started in, which is a different and much larger claim. if settings.Default().Autosave { t.Error("settings.Default() autosaves; a project with no settings file never opted in") } } // --- the contract the three templates are held to --------------------------- // The three embedded templates and the blanks profile.Templates says each one // takes. Kept together so that adding a verb to a .tmpl file without saying so // here fails, which is the guard the constants used to get for free by sitting // next to the contract. var embeddedTemplates = []struct { name string body string verb string blanks int filledBy []any }{ {"settings.toml.tmpl", settingsTemplate, "%q", 2, []any{"turbo-classic", "2s"}}, {"snippets.toml.tmpl", snippetsTemplate, "%s", 2, []any{"General", "/tmp/snippets.toml"}}, {"tools.toml.tmpl", toolsTemplate, "%", 0, nil}, } func TestEveryTemplateIsEmbeddedAndNotEmpty(t *testing.T) { // go:embed fails to compile when a file is missing, but an empty file // compiles happily and writes an empty starter file into somebody's // project. for _, template := range embeddedTemplates { if len(template.body) == 0 { t.Errorf("%s embedded as nothing", template.name) } } } func TestEveryTemplateTakesTheBlanksItsContractPromises(t *testing.T) { // profile.Templates documents the count and the verb of each. The templates // live in files of their own, so nothing but this notices a verb added, // removed, or changed. for _, template := range embeddedTemplates { if got := strings.Count(template.body, template.verb); got != template.blanks { t.Errorf("%s holds %d %q, want %d", template.name, got, template.verb, template.blanks) } } } func TestFillingATemplateLeavesNoFormattingMarker(t *testing.T) { // Go writes %!q(MISSING) or %!(EXTRA …) into the output rather than // failing, so a template with the wrong number of blanks produces a file // that is written, opened, and wrong. for _, template := range embeddedTemplates { filled := template.body if template.filledBy != nil { filled = fmt.Sprintf(template.body, template.filledBy...) } if strings.Contains(filled, "%!") { t.Errorf("%s filled to:\n%s", template.name, filled) } } } func TestEveryTemplateNamesThisEditorAndNotTheOnesItWasAdaptedFrom(t *testing.T) { // The three templates started as Turbo Rust's. A leftover "turbo-rust" in a // file written into somebody's Python project is the whole class of mistake // this catches. templates := map[string]string{ "settings": settingsTemplate, "snippets": snippetsTemplate, "tools": toolsTemplate, } for name, template := range templates { t.Run(name, func(t *testing.T) { for _, other := range []string{"turbo-go", "turbo-rust", "cargo", "gopls", "rust-analyzer"} { if strings.Contains(template, other) { t.Errorf("the %s template still says %q:\n%s", name, other, template) } } if !strings.Contains(template, Slug) { t.Errorf("the %s template never names %s:\n%s", name, Slug, template) } }) } }