refactor: merge net and http under runtime module

This commit is contained in:
Jan De Dobbeleer 2024-07-03 09:04:11 +02:00 committed by Jan De Dobbeleer
parent 05251e1ac3
commit 822e2b5b48
106 changed files with 1266 additions and 1170 deletions

49
src/cache/cache.go vendored Normal file
View file

@ -0,0 +1,49 @@
package cache
import (
"fmt"
"os"
"strconv"
"time"
)
type Cache interface {
Init(home string)
Close()
// Gets the value for a given key.
// Returns the value and a boolean indicating if the key was found.
// In case the ttl expired, the function returns false.
Get(key string) (string, bool)
// Sets a value for a given key.
// The ttl indicates how many minutes to cache the value.
Set(key, value string, ttl int)
// Deletes a key from the cache.
Delete(key string)
}
func pid() string {
pid := os.Getenv("POSH_PID")
if len(pid) == 0 {
pid = strconv.Itoa(os.Getppid())
}
return pid
}
var (
TEMPLATECACHE = fmt.Sprintf("template_cache_%s", pid())
TOGGLECACHE = fmt.Sprintf("toggle_cache_%s", pid())
PROMPTCOUNTCACHE = fmt.Sprintf("prompt_count_cache_%s", pid())
)
type Entry struct {
Value string `json:"value"`
Timestamp int64 `json:"timestamp"`
TTL int `json:"ttl"`
}
func (c *Entry) Expired() bool {
if c.TTL < 0 {
return false
}
return time.Now().Unix() >= (c.Timestamp + int64(c.TTL)*60)
}

20
src/cache/command.go vendored Normal file
View file

@ -0,0 +1,20 @@
package cache
import "github.com/jandedobbeleer/oh-my-posh/src/concurrent"
type Command struct {
Commands *concurrent.Map
}
func (c *Command) Set(command, path string) {
c.Commands.Set(command, path)
}
func (c *Command) Get(command string) (string, bool) {
cacheCommand, found := c.Commands.Get(command)
if !found {
return "", false
}
command, ok := cacheCommand.(string)
return command, ok
}

85
src/cache/file.go vendored Normal file
View file

@ -0,0 +1,85 @@
package cache
import (
"encoding/json"
"os"
"path/filepath"
"time"
"github.com/jandedobbeleer/oh-my-posh/src/concurrent"
)
const (
CacheFile = "/omp.cache"
)
type File struct {
cache *concurrent.Map
cachePath string
dirty bool
}
func (fc *File) Init(cachePath string) {
fc.cache = concurrent.NewMap()
fc.cachePath = cachePath
cacheFilePath := filepath.Join(fc.cachePath, CacheFile)
content, err := os.ReadFile(cacheFilePath)
if err != nil {
return
}
var list map[string]*Entry
if err := json.Unmarshal(content, &list); err != nil {
return
}
for key, co := range list {
if co.Expired() {
continue
}
fc.cache.Set(key, co)
}
}
func (fc *File) Close() {
if !fc.dirty {
return
}
cache := fc.cache.ToSimpleMap()
if dump, err := json.MarshalIndent(cache, "", " "); err == nil {
cacheFilePath := filepath.Join(fc.cachePath, CacheFile)
_ = os.WriteFile(cacheFilePath, dump, 0644)
}
}
// returns the value for the given key as long as
// the TTL (minutes) is not expired
func (fc *File) Get(key string) (string, bool) {
val, found := fc.cache.Get(key)
if !found {
return "", false
}
if co, ok := val.(*Entry); ok {
return co.Value, true
}
return "", false
}
// sets the value for the given key with a TTL (minutes)
func (fc *File) Set(key, value string, ttl int) {
fc.cache.Set(key, &Entry{
Value: value,
Timestamp: time.Now().Unix(),
TTL: ttl,
})
fc.dirty = true
}
// delete the key from the cache
func (fc *File) Delete(key string) {
fc.cache.Delete(key)
fc.dirty = true
}

View file

@ -2,18 +2,18 @@ package mock
import mock "github.com/stretchr/testify/mock" import mock "github.com/stretchr/testify/mock"
// MockedCache is an autogenerated mock type for the cache type // Cache is an autogenerated mock type for the cache type
type MockedCache struct { type Cache struct {
mock.Mock mock.Mock
} }
// close provides a mock function with given fields: // close provides a mock function with given fields:
func (_m *MockedCache) Close() { func (_m *Cache) Close() {
_m.Called() _m.Called()
} }
// get provides a mock function with given fields: key // get provides a mock function with given fields: key
func (_m *MockedCache) Get(key string) (string, bool) { func (_m *Cache) Get(key string) (string, bool) {
ret := _m.Called(key) ret := _m.Called(key)
var r0 string var r0 string
@ -34,16 +34,16 @@ func (_m *MockedCache) Get(key string) (string, bool) {
} }
// init provides a mock function with given fields: home // init provides a mock function with given fields: home
func (_m *MockedCache) Init(home string) { func (_m *Cache) Init(home string) {
_m.Called(home) _m.Called(home)
} }
// set provides a mock function with given fields: key, value, ttl // set provides a mock function with given fields: key, value, ttl
func (_m *MockedCache) Set(key, value string, ttl int) { func (_m *Cache) Set(key, value string, ttl int) {
_m.Called(key, value, ttl) _m.Called(key, value, ttl)
} }
// delete provides a mock function with given fields: key // delete provides a mock function with given fields: key
func (_m *MockedCache) Delete(key string) { func (_m *Cache) Delete(key string) {
_m.Called(key) _m.Called(key)
} }

38
src/cache/template.go vendored Normal file
View file

@ -0,0 +1,38 @@
package cache
import (
"sync"
"github.com/jandedobbeleer/oh-my-posh/src/concurrent"
)
type Template struct {
Root bool
PWD string
AbsolutePWD string
Folder string
Shell string
ShellVersion string
UserName string
HostName string
Code int
Env map[string]string
Var concurrent.SimpleMap
OS string
WSL bool
PromptCount int
SHLVL int
Segments *concurrent.Map
SegmentsCache concurrent.SimpleMap
Initialized bool
sync.RWMutex
}
func (t *Template) AddSegmentData(key string, value any) {
t.Segments.Set(key, value)
}
func (t *Template) RemoveSegmentData(key string) {
t.Segments.Delete(key)
}

View file

@ -7,6 +7,7 @@ import (
"path/filepath" "path/filepath"
"strings" "strings"
"github.com/jandedobbeleer/oh-my-posh/src/cache"
"github.com/jandedobbeleer/oh-my-posh/src/runtime" "github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/spf13/cobra" "github.com/spf13/cobra"
@ -43,7 +44,7 @@ You can do the following:
case "path": case "path":
fmt.Print(env.CachePath()) fmt.Print(env.CachePath())
case "clear": case "clear":
cacheFilePath := filepath.Join(env.CachePath(), runtime.CacheFile) cacheFilePath := filepath.Join(env.CachePath(), cache.CacheFile)
err := os.Remove(cacheFilePath) err := os.Remove(cacheFilePath)
if err != nil { if err != nil {
fmt.Println(err.Error()) fmt.Println(err.Error())
@ -51,7 +52,7 @@ You can do the following:
} }
fmt.Printf("removed cache file at %s\n", cacheFilePath) fmt.Printf("removed cache file at %s\n", cacheFilePath)
case "edit": case "edit":
cacheFilePath := filepath.Join(env.CachePath(), runtime.CacheFile) cacheFilePath := filepath.Join(env.CachePath(), cache.CacheFile)
editFileWithEditor(cacheFilePath) editFileWithEditor(cacheFilePath)
} }
}, },

View file

@ -5,6 +5,7 @@ import (
"strings" "strings"
"time" "time"
"github.com/jandedobbeleer/oh-my-posh/src/cache"
"github.com/jandedobbeleer/oh-my-posh/src/color" "github.com/jandedobbeleer/oh-my-posh/src/color"
"github.com/jandedobbeleer/oh-my-posh/src/runtime" "github.com/jandedobbeleer/oh-my-posh/src/runtime"
@ -64,8 +65,7 @@ This command is used to get the value of the following variables:
accent := color2.RGB(rgb.R, rgb.G, rgb.B) accent := color2.RGB(rgb.R, rgb.G, rgb.B)
fmt.Println("#" + accent.Hex()) fmt.Println("#" + accent.Hex())
case "toggles": case "toggles":
cache := env.Cache() togglesCache, _ := env.Cache().Get(cache.TOGGLECACHE)
togglesCache, _ := cache.Get(runtime.TOGGLECACHE)
var toggles []string var toggles []string
if len(togglesCache) != 0 { if len(togglesCache) != 0 {
toggles = strings.Split(togglesCache, ",") toggles = strings.Split(togglesCache, ",")

View file

@ -3,6 +3,7 @@ package cli
import ( import (
"strings" "strings"
"github.com/jandedobbeleer/oh-my-posh/src/cache"
"github.com/jandedobbeleer/oh-my-posh/src/runtime" "github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
@ -22,8 +23,7 @@ var toggleCmd = &cobra.Command{
env.Init() env.Init()
defer env.Close() defer env.Close()
cache := env.Cache() togglesCache, _ := env.Cache().Get(cache.TOGGLECACHE)
togglesCache, _ := cache.Get(runtime.TOGGLECACHE)
var toggles []string var toggles []string
if len(togglesCache) != 0 { if len(togglesCache) != 0 {
toggles = strings.Split(togglesCache, ",") toggles = strings.Split(togglesCache, ",")
@ -44,7 +44,7 @@ var toggleCmd = &cobra.Command{
newToggles = append(newToggles, segment) newToggles = append(newToggles, segment)
} }
cache.Set(runtime.TOGGLECACHE, strings.Join(newToggles, ","), 1440) env.Cache().Set(cache.TOGGLECACHE, strings.Join(newToggles, ","), 1440)
}, },
} }

View file

@ -5,8 +5,8 @@ import (
"testing" "testing"
"github.com/alecthomas/assert" "github.com/alecthomas/assert"
"github.com/jandedobbeleer/oh-my-posh/src/mock"
"github.com/jandedobbeleer/oh-my-posh/src/runtime" "github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
) )
func TestGetAnsiFromColorString(t *testing.T) { func TestGetAnsiFromColorString(t *testing.T) {
@ -38,7 +38,7 @@ func TestGetAnsiFromColorString(t *testing.T) {
} }
func TestMakeColors(t *testing.T) { func TestMakeColors(t *testing.T) {
env := &mock.MockedEnvironment{} env := &mock.Environment{}
env.On("WindowsRegistryKeyValue", `HKEY_CURRENT_USER\Software\Microsoft\Windows\DWM\ColorizationColor`).Return(&runtime.WindowsRegistryValue{}, errors.New("err")) env.On("WindowsRegistryKeyValue", `HKEY_CURRENT_USER\Software\Microsoft\Windows\DWM\ColorizationColor`).Return(&runtime.WindowsRegistryValue{}, errors.New("err"))
colors := MakeColors(nil, false, "", env) colors := MakeColors(nil, false, "", env)

46
src/concurrent/map.go Normal file
View file

@ -0,0 +1,46 @@
package concurrent
import "sync"
func NewMap() *Map {
var cm Map
return &cm
}
type Map sync.Map
func (cm *Map) Set(key string, value any) {
(*sync.Map)(cm).Store(key, value)
}
func (cm *Map) Get(key string) (any, bool) {
return (*sync.Map)(cm).Load(key)
}
func (cm *Map) Delete(key string) {
(*sync.Map)(cm).Delete(key)
}
func (cm *Map) Contains(key string) bool {
_, ok := (*sync.Map)(cm).Load(key)
return ok
}
func (cm *Map) ToSimpleMap() SimpleMap {
list := make(map[string]any)
(*sync.Map)(cm).Range(func(key, value any) bool {
list[key.(string)] = value
return true
})
return list
}
type SimpleMap map[string]any
func (m SimpleMap) ConcurrentMap() *Map {
var cm Map
for k, v := range m {
cm.Set(k, v)
}
return &cm
}

View file

@ -3,12 +3,12 @@ package config
import ( import (
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/cache"
"github.com/jandedobbeleer/oh-my-posh/src/color" "github.com/jandedobbeleer/oh-my-posh/src/color"
"github.com/jandedobbeleer/oh-my-posh/src/mock" "github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
mock2 "github.com/stretchr/testify/mock" testify_ "github.com/stretchr/testify/mock"
) )
func TestGetPalette(t *testing.T) { func TestGetPalette(t *testing.T) {
@ -70,12 +70,12 @@ func TestGetPalette(t *testing.T) {
}, },
} }
for _, tc := range cases { for _, tc := range cases {
env := &mock.MockedEnvironment{} env := &mock.Environment{}
env.On("TemplateCache").Return(&runtime.TemplateCache{ env.On("TemplateCache").Return(&cache.Template{
Env: map[string]string{}, Env: map[string]string{},
Shell: "bash", Shell: "bash",
}) })
env.On("DebugF", mock2.Anything, mock2.Anything).Return(nil) env.On("DebugF", testify_.Anything, testify_.Anything).Return(nil)
cfg := &Config{ cfg := &Config{
env: env, env: env,
Palette: tc.Palette, Palette: tc.Palette,

View file

@ -4,12 +4,12 @@ import (
"context" "context"
"fmt" "fmt"
"io" "io"
"net/http" httplib "net/http"
"strconv" "strconv"
"strings" "strings"
"time" "time"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/net" "github.com/jandedobbeleer/oh-my-posh/src/runtime/http"
) )
type ConnectionError struct { type ConnectionError struct {
@ -28,12 +28,12 @@ func getGlyphCodePoints() (codePoints, error) {
ctx, cncl := context.WithTimeout(context.Background(), time.Millisecond*time.Duration(5000)) ctx, cncl := context.WithTimeout(context.Background(), time.Millisecond*time.Duration(5000))
defer cncl() defer cncl()
request, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://ohmyposh.dev/codepoints.csv", nil) request, err := httplib.NewRequestWithContext(ctx, httplib.MethodGet, "https://ohmyposh.dev/codepoints.csv", nil)
if err != nil { if err != nil {
return codePoints, &ConnectionError{reason: err.Error()} return codePoints, &ConnectionError{reason: err.Error()}
} }
response, err := net.HTTPClient.Do(request) response, err := http.HTTPClient.Do(request)
if err != nil { if err != nil {
return codePoints, err return codePoints, err
} }

View file

@ -3,13 +3,13 @@ package config
import ( import (
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime" "github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/jandedobbeleer/oh-my-posh/src/segments" "github.com/jandedobbeleer/oh-my-posh/src/segments"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
mock2 "github.com/stretchr/testify/mock" testify_ "github.com/stretchr/testify/mock"
) )
const ( const (
@ -327,8 +327,8 @@ func TestSegmentTemplateMigration(t *testing.T) {
Type: tc.Type, Type: tc.Type,
Properties: tc.Props, Properties: tc.Props,
} }
env := &mock.MockedEnvironment{} env := &mock.Environment{}
env.On("Debug", mock2.Anything).Return(nil) env.On("Debug", testify_.Anything).Return(nil)
segment.migrationOne(env) segment.migrationOne(env)
assert.Equal(t, tc.Expected, segment.Properties[segmentTemplate], tc.Case) assert.Equal(t, tc.Expected, segment.Properties[segmentTemplate], tc.Case)
} }
@ -431,7 +431,7 @@ func TestMigrateConfig(t *testing.T) {
for _, tc := range cases { for _, tc := range cases {
cfg := &Config{ cfg := &Config{
ConsoleTitleTemplate: tc.Template, ConsoleTitleTemplate: tc.Template,
env: &mock.MockedEnvironment{}, env: &mock.Environment{},
} }
cfg.Migrate() cfg.Migrate()
assert.Equal(t, tc.Expected, cfg.ConsoleTitleTemplate, tc.Case) assert.Equal(t, tc.Expected, cfg.ConsoleTitleTemplate, tc.Case)
@ -465,7 +465,7 @@ func TestMigrationTwo(t *testing.T) {
if tc.Template != "" { if tc.Template != "" {
segment.Properties[segmentTemplate] = tc.Template segment.Properties[segmentTemplate] = tc.Template
} }
segment.migrationTwo(&mock.MockedEnvironment{}) segment.migrationTwo(&mock.Environment{})
assert.Equal(t, tc.Expected, segment.Template, tc.Case) assert.Equal(t, tc.Expected, segment.Template, tc.Case)
assert.NotContains(t, segment.Properties, segmentTemplate, tc.Case) assert.NotContains(t, segment.Properties, segmentTemplate, tc.Case)
} }

View file

@ -3,7 +3,7 @@ package config
import ( import (
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock" "github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -27,7 +27,7 @@ func TestShouldHideForWidth(t *testing.T) {
{Case: "Min & Max cols - show", MinWidth: 10, MaxWidth: 20, Width: 11, Expected: false}, {Case: "Min & Max cols - show", MinWidth: 10, MaxWidth: 20, Width: 11, Expected: false},
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("TerminalWidth").Return(tc.Width, tc.Error) env.On("TerminalWidth").Return(tc.Width, tc.Error)
got := shouldHideForWidth(env, tc.MinWidth, tc.MaxWidth) got := shouldHideForWidth(env, tc.MinWidth, tc.MaxWidth)
assert.Equal(t, tc.Expected, got, tc.Case) assert.Equal(t, tc.Expected, got, tc.Case)

View file

@ -6,6 +6,7 @@ import (
"strings" "strings"
"time" "time"
"github.com/jandedobbeleer/oh-my-posh/src/cache"
"github.com/jandedobbeleer/oh-my-posh/src/color" "github.com/jandedobbeleer/oh-my-posh/src/color"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime" "github.com/jandedobbeleer/oh-my-posh/src/runtime"
@ -112,7 +113,7 @@ func (segment *Segment) SetEnabled(env runtime.Environment) {
segment.env.DebugF("Segment: %s", segment.Name()) segment.env.DebugF("Segment: %s", segment.Name())
// validate toggles // validate toggles
if toggles, OK := segment.env.Cache().Get(runtime.TOGGLECACHE); OK && len(toggles) > 0 { if toggles, OK := segment.env.Cache().Get(cache.TOGGLECACHE); OK && len(toggles) > 0 {
list := strings.Split(toggles, ",") list := strings.Split(toggles, ",")
for _, toggle := range list { for _, toggle := range list {
if SegmentType(toggle) == segment.Type || toggle == segment.Alias { if SegmentType(toggle) == segment.Type || toggle == segment.Alias {

View file

@ -4,14 +4,15 @@ import (
"encoding/json" "encoding/json"
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/cache"
"github.com/jandedobbeleer/oh-my-posh/src/color" "github.com/jandedobbeleer/oh-my-posh/src/color"
"github.com/jandedobbeleer/oh-my-posh/src/mock"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime" "github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/jandedobbeleer/oh-my-posh/src/segments" "github.com/jandedobbeleer/oh-my-posh/src/segments"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
mock2 "github.com/stretchr/testify/mock" testify_ "github.com/stretchr/testify/mock"
) )
const ( const (
@ -22,7 +23,7 @@ func TestMapSegmentWriterCanMap(t *testing.T) {
sc := &Segment{ sc := &Segment{
Type: SESSION, Type: SESSION,
} }
env := new(mock.MockedEnvironment) env := new(mock.Environment)
err := sc.MapSegmentWithWriter(env) err := sc.MapSegmentWithWriter(env)
assert.NoError(t, err) assert.NoError(t, err)
assert.NotNil(t, sc.writer) assert.NotNil(t, sc.writer)
@ -32,7 +33,7 @@ func TestMapSegmentWriterCannotMap(t *testing.T) {
sc := &Segment{ sc := &Segment{
Type: "nilwriter", Type: "nilwriter",
} }
env := new(mock.MockedEnvironment) env := new(mock.Environment)
err := sc.MapSegmentWithWriter(env) err := sc.MapSegmentWithWriter(env)
assert.Error(t, err) assert.Error(t, err)
} }
@ -72,7 +73,7 @@ func TestShouldIncludeFolder(t *testing.T) {
{Case: "!Include & !Exclude", Included: false, Excluded: false, Expected: false}, {Case: "!Include & !Exclude", Included: false, Excluded: false, Expected: false},
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("GOOS").Return(runtime.LINUX) env.On("GOOS").Return(runtime.LINUX)
env.On("Home").Return("") env.On("Home").Return("")
env.On("Pwd").Return(cwd) env.On("Pwd").Return(cwd)
@ -143,9 +144,9 @@ func TestGetColors(t *testing.T) {
}, },
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("DebugF", mock2.Anything, mock2.Anything).Return(nil) env.On("DebugF", testify_.Anything, testify_.Anything).Return(nil)
env.On("TemplateCache").Return(&runtime.TemplateCache{ env.On("TemplateCache").Return(&cache.Template{
Env: make(map[string]string), Env: make(map[string]string),
}) })

View file

@ -319,7 +319,6 @@ func (segment *Segment) MapSegmentWithWriter(env runtime.Environment) error {
writer := f() writer := f()
wrapper := &properties.Wrapper{ wrapper := &properties.Wrapper{
Properties: segment.Properties, Properties: segment.Properties,
Env: env,
} }
writer.Init(wrapper, env) writer.Init(wrapper, env)
segment.writer = writer segment.writer = writer

View file

@ -8,10 +8,10 @@ import (
"errors" "errors"
"fmt" "fmt"
"io" "io"
"net/http" httplib "net/http"
"net/url" "net/url"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/net" "github.com/jandedobbeleer/oh-my-posh/src/runtime/http"
) )
func Download(fontPath string) ([]byte, error) { func Download(fontPath string) ([]byte, error) {
@ -33,22 +33,22 @@ func Download(fontPath string) ([]byte, error) {
} }
func isZipFile(data []byte) bool { func isZipFile(data []byte) bool {
contentType := http.DetectContentType(data) contentType := httplib.DetectContentType(data)
return contentType == "application/zip" return contentType == "application/zip"
} }
func getRemoteFile(location string) (data []byte, err error) { func getRemoteFile(location string) (data []byte, err error) {
req, err := http.NewRequestWithContext(context.Background(), "GET", location, nil) req, err := httplib.NewRequestWithContext(context.Background(), "GET", location, nil)
if err != nil { if err != nil {
return nil, err return nil, err
} }
resp, err := net.HTTPClient.Do(req) resp, err := http.HTTPClient.Do(req)
if err != nil { if err != nil {
return return
} }
defer resp.Body.Close() defer resp.Body.Close()
if resp.StatusCode != http.StatusOK { if resp.StatusCode != httplib.StatusOK {
return data, fmt.Errorf("Failed to download zip file: %s\n→ %s", resp.Status, location) return data, fmt.Errorf("Failed to download zip file: %s\n→ %s", resp.Status, location)
} }

View file

@ -5,12 +5,12 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"net/http" httplib "net/http"
"sort" "sort"
"strings" "strings"
"time" "time"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/net" "github.com/jandedobbeleer/oh-my-posh/src/runtime/http"
) )
type release struct { type release struct {
@ -51,14 +51,14 @@ func fetchFontAssets(repo string) ([]*Asset, error) {
defer cancelF() defer cancelF()
repoURL := "https://api.github.com/repos/" + repo + "/releases/latest" repoURL := "https://api.github.com/repos/" + repo + "/releases/latest"
req, err := http.NewRequestWithContext(ctx, "GET", repoURL, nil) req, err := httplib.NewRequestWithContext(ctx, "GET", repoURL, nil)
if err != nil { if err != nil {
return nil, err return nil, err
} }
req.Header.Add("Accept", "application/vnd.github.v3+json") req.Header.Add("Accept", "application/vnd.github.v3+json")
response, err := net.HTTPClient.Do(req) response, err := http.HTTPClient.Do(req)
if err != nil || response.StatusCode != http.StatusOK { if err != nil || response.StatusCode != httplib.StatusOK {
return nil, fmt.Errorf("failed to get %s release", repo) return nil, fmt.Errorf("failed to get %s release", repo)
} }

View file

@ -1,70 +0,0 @@
package http
import (
"encoding/json"
"errors"
"io"
"github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
)
type Request struct {
props properties.Properties
env runtime.Environment
}
func (r *Request) Init(env runtime.Environment, props properties.Properties) {
r.env = env
r.props = props
}
func Do[a any](r *Request, url string, requestModifiers ...runtime.HTTPRequestModifier) (a, error) {
if data, err := getCacheValue[a](r, url); err == nil {
return data, nil
}
return do[a](r, url, nil, requestModifiers...)
}
func getCacheValue[a any](r *Request, key string) (a, error) {
var data a
cacheTimeout := r.props.GetInt(properties.CacheTimeout, 30)
if cacheTimeout <= 0 {
return data, errors.New("no cache needed")
}
if val, found := r.env.Cache().Get(key); found {
err := json.Unmarshal([]byte(val), &data)
if err != nil {
r.env.Error(err)
return data, err
}
return data, nil
}
err := errors.New("no data in cache")
r.env.Error(err)
return data, err
}
func do[a any](r *Request, url string, body io.Reader, requestModifiers ...runtime.HTTPRequestModifier) (a, error) {
var data a
httpTimeout := r.props.GetInt(properties.HTTPTimeout, properties.DefaultHTTPTimeout)
responseBody, err := r.env.HTTPRequest(url, body, httpTimeout, requestModifiers...)
if err != nil {
r.env.Error(err)
return data, err
}
err = json.Unmarshal(responseBody, &data)
if err != nil {
r.env.Error(err)
return data, err
}
cacheTimeout := r.props.GetInt(properties.CacheTimeout, 30)
if cacheTimeout > 0 {
r.env.Cache().Set(url, string(responseBody), cacheTimeout)
}
return data, nil
}

View file

@ -1,293 +0,0 @@
package mock
import (
"io"
"io/fs"
"time"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/battery"
mock "github.com/stretchr/testify/mock"
)
type MockedEnvironment struct {
mock.Mock
}
func (env *MockedEnvironment) Getenv(key string) string {
args := env.Called(key)
return args.String(0)
}
func (env *MockedEnvironment) Pwd() string {
args := env.Called()
return args.String(0)
}
func (env *MockedEnvironment) Home() string {
args := env.Called()
return args.String(0)
}
func (env *MockedEnvironment) HasFiles(pattern string) bool {
args := env.Called(pattern)
return args.Bool(0)
}
func (env *MockedEnvironment) HasFilesInDir(dir, pattern string) bool {
args := env.Called(dir, pattern)
return args.Bool(0)
}
func (env *MockedEnvironment) HasFolder(folder string) bool {
args := env.Called(folder)
return args.Bool(0)
}
func (env *MockedEnvironment) ResolveSymlink(path string) (string, error) {
args := env.Called(path)
return args.String(0), args.Error(1)
}
func (env *MockedEnvironment) FileContent(file string) string {
args := env.Called(file)
return args.String(0)
}
func (env *MockedEnvironment) LsDir(path string) []fs.DirEntry {
args := env.Called(path)
return args.Get(0).([]fs.DirEntry)
}
func (env *MockedEnvironment) PathSeparator() string {
args := env.Called()
return args.String(0)
}
func (env *MockedEnvironment) User() string {
args := env.Called()
return args.String(0)
}
func (env *MockedEnvironment) Host() (string, error) {
args := env.Called()
return args.String(0), args.Error(1)
}
func (env *MockedEnvironment) GOOS() string {
args := env.Called()
return args.String(0)
}
func (env *MockedEnvironment) Platform() string {
args := env.Called()
return args.String(0)
}
func (env *MockedEnvironment) CommandPath(command string) string {
args := env.Called(command)
return args.String(0)
}
func (env *MockedEnvironment) HasCommand(command string) bool {
args := env.Called(command)
return args.Bool(0)
}
func (env *MockedEnvironment) RunCommand(command string, args ...string) (string, error) {
arguments := env.Called(command, args)
return arguments.String(0), arguments.Error(1)
}
func (env *MockedEnvironment) RunShellCommand(shell, command string) string {
args := env.Called(shell, command)
return args.String(0)
}
func (env *MockedEnvironment) StatusCodes() (int, string) {
args := env.Called()
return args.Int(0), args.String(1)
}
func (env *MockedEnvironment) ExecutionTime() float64 {
args := env.Called()
return float64(args.Int(0))
}
func (env *MockedEnvironment) Root() bool {
args := env.Called()
return args.Bool(0)
}
func (env *MockedEnvironment) Flags() *runtime.Flags {
arguments := env.Called()
return arguments.Get(0).(*runtime.Flags)
}
func (env *MockedEnvironment) BatteryState() (*battery.Info, error) {
args := env.Called()
return args.Get(0).(*battery.Info), args.Error(1)
}
func (env *MockedEnvironment) Shell() string {
args := env.Called()
return args.String(0)
}
func (env *MockedEnvironment) QueryWindowTitles(processName, windowTitleRegex string) (string, error) {
args := env.Called(processName, windowTitleRegex)
return args.String(0), args.Error(1)
}
func (env *MockedEnvironment) WindowsRegistryKeyValue(path string) (*runtime.WindowsRegistryValue, error) {
args := env.Called(path)
return args.Get(0).(*runtime.WindowsRegistryValue), args.Error(1)
}
func (env *MockedEnvironment) HTTPRequest(url string, _ io.Reader, _ int, _ ...runtime.HTTPRequestModifier) ([]byte, error) {
args := env.Called(url)
return args.Get(0).([]byte), args.Error(1)
}
func (env *MockedEnvironment) HasParentFilePath(path string) (*runtime.FileInfo, error) {
args := env.Called(path)
return args.Get(0).(*runtime.FileInfo), args.Error(1)
}
func (env *MockedEnvironment) StackCount() int {
args := env.Called()
return args.Int(0)
}
func (env *MockedEnvironment) IsWsl() bool {
args := env.Called()
return args.Bool(0)
}
func (env *MockedEnvironment) IsWsl2() bool {
args := env.Called()
return args.Bool(0)
}
func (env *MockedEnvironment) TerminalWidth() (int, error) {
args := env.Called()
return args.Int(0), args.Error(1)
}
func (env *MockedEnvironment) CachePath() string {
args := env.Called()
return args.String(0)
}
func (env *MockedEnvironment) Cache() runtime.Cache {
args := env.Called()
return args.Get(0).(runtime.Cache)
}
func (env *MockedEnvironment) Close() {
_ = env.Called()
}
func (env *MockedEnvironment) Logs() string {
args := env.Called()
return args.String(0)
}
func (env *MockedEnvironment) InWSLSharedDrive() bool {
args := env.Called()
return args.Bool(0)
}
func (env *MockedEnvironment) ConvertToWindowsPath(_ string) string {
args := env.Called()
return args.String(0)
}
func (env *MockedEnvironment) ConvertToLinuxPath(_ string) string {
args := env.Called()
return args.String(0)
}
func (env *MockedEnvironment) Connection(connectionType runtime.ConnectionType) (*runtime.Connection, error) {
args := env.Called(connectionType)
return args.Get(0).(*runtime.Connection), args.Error(1)
}
func (env *MockedEnvironment) TemplateCache() *runtime.TemplateCache {
args := env.Called()
return args.Get(0).(*runtime.TemplateCache)
}
func (env *MockedEnvironment) LoadTemplateCache() {
_ = env.Called()
}
func (env *MockedEnvironment) MockGitCommand(dir, returnValue string, args ...string) {
args = append([]string{"-C", dir, "--no-optional-locks", "-c", "core.quotepath=false", "-c", "color.status=false"}, args...)
env.On("RunCommand", "git", args).Return(returnValue, nil)
}
func (env *MockedEnvironment) MockHgCommand(dir, returnValue string, args ...string) {
args = append([]string{"-R", dir}, args...)
env.On("RunCommand", "hg", args).Return(returnValue, nil)
}
func (env *MockedEnvironment) MockSvnCommand(dir, returnValue string, args ...string) {
args = append([]string{"-C", dir, "--no-optional-locks", "-c", "core.quotepath=false", "-c", "color.status=false"}, args...)
env.On("RunCommand", "svn", args).Return(returnValue, nil)
}
func (env *MockedEnvironment) HasFileInParentDirs(pattern string, depth uint) bool {
args := env.Called(pattern, depth)
return args.Bool(0)
}
func (env *MockedEnvironment) DirMatchesOneOf(dir string, regexes []string) bool {
args := env.Called(dir, regexes)
return args.Bool(0)
}
func (env *MockedEnvironment) Trace(start time.Time, args ...string) {
_ = env.Called(start, args)
}
func (env *MockedEnvironment) Debug(message string) {
_ = env.Called(message)
}
func (env *MockedEnvironment) DebugF(format string, a ...any) {
_ = env.Called(format, a)
}
func (env *MockedEnvironment) Error(err error) {
_ = env.Called(err)
}
func (env *MockedEnvironment) DirIsWritable(path string) bool {
args := env.Called(path)
return args.Bool(0)
}
func (env *MockedEnvironment) SetPromptCount() {
_ = env.Called()
}
func (env *MockedEnvironment) CursorPosition() (int, int) {
args := env.Called()
return args.Int(0), args.Int(1)
}
func (env *MockedEnvironment) SystemInfo() (*runtime.SystemInfo, error) {
args := env.Called()
return args.Get(0).(*runtime.SystemInfo), args.Error(1)
}
func (env *MockedEnvironment) Unset(name string) {
for i := 0; i < len(env.ExpectedCalls); i++ {
f := env.ExpectedCalls[i]
if f.Method == name {
f.Unset()
}
}
}

View file

@ -4,14 +4,15 @@ import (
"errors" "errors"
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/cache"
"github.com/jandedobbeleer/oh-my-posh/src/config" "github.com/jandedobbeleer/oh-my-posh/src/config"
"github.com/jandedobbeleer/oh-my-posh/src/mock"
"github.com/jandedobbeleer/oh-my-posh/src/runtime" "github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/jandedobbeleer/oh-my-posh/src/shell" "github.com/jandedobbeleer/oh-my-posh/src/shell"
"github.com/jandedobbeleer/oh-my-posh/src/terminal" "github.com/jandedobbeleer/oh-my-posh/src/terminal"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
mock2 "github.com/stretchr/testify/mock" testify_ "github.com/stretchr/testify/mock"
) )
func TestCanWriteRPrompt(t *testing.T) { func TestCanWriteRPrompt(t *testing.T) {
@ -33,7 +34,7 @@ func TestCanWriteRPrompt(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("TerminalWidth").Return(tc.TerminalWidth, tc.TerminalWidthError) env.On("TerminalWidth").Return(tc.TerminalWidth, tc.TerminalWidthError)
engine := &Engine{ engine := &Engine{
Env: env, Env: env,
@ -72,7 +73,7 @@ func TestPrintPWD(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
if len(tc.Pwd) == 0 { if len(tc.Pwd) == 0 {
tc.Pwd = "pwd" tc.Pwd = "pwd"
} }
@ -80,8 +81,8 @@ func TestPrintPWD(t *testing.T) {
env.On("Shell").Return(tc.Shell) env.On("Shell").Return(tc.Shell)
env.On("User").Return("user") env.On("User").Return("user")
env.On("Host").Return("host", nil) env.On("Host").Return("host", nil)
env.On("DebugF", mock2.Anything, mock2.Anything).Return(nil) env.On("DebugF", testify_.Anything, testify_.Anything).Return(nil)
env.On("TemplateCache").Return(&runtime.TemplateCache{ env.On("TemplateCache").Return(&cache.Template{
Env: make(map[string]string), Env: make(map[string]string),
Shell: "shell", Shell: "shell",
}) })
@ -170,12 +171,12 @@ func TestGetTitle(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("Pwd").Return(tc.Cwd) env.On("Pwd").Return(tc.Cwd)
env.On("Home").Return("/usr/home") env.On("Home").Return("/usr/home")
env.On("PathSeparator").Return(tc.PathSeparator) env.On("PathSeparator").Return(tc.PathSeparator)
env.On("DebugF", mock2.Anything, mock2.Anything).Return(nil) env.On("DebugF", testify_.Anything, testify_.Anything).Return(nil)
env.On("TemplateCache").Return(&runtime.TemplateCache{ env.On("TemplateCache").Return(&cache.Template{
Env: map[string]string{ Env: map[string]string{
"USERDOMAIN": "MyCompany", "USERDOMAIN": "MyCompany",
}, },
@ -234,11 +235,11 @@ func TestGetConsoleTitleIfGethostnameReturnsError(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("Pwd").Return(tc.Cwd) env.On("Pwd").Return(tc.Cwd)
env.On("Home").Return("/usr/home") env.On("Home").Return("/usr/home")
env.On("DebugF", mock2.Anything, mock2.Anything).Return(nil) env.On("DebugF", testify_.Anything, testify_.Anything).Return(nil)
env.On("TemplateCache").Return(&runtime.TemplateCache{ env.On("TemplateCache").Return(&cache.Template{
Env: map[string]string{ Env: map[string]string{
"USERDOMAIN": "MyCompany", "USERDOMAIN": "MyCompany",
}, },

View file

@ -4,58 +4,57 @@ import (
"fmt" "fmt"
"github.com/jandedobbeleer/oh-my-posh/src/color" "github.com/jandedobbeleer/oh-my-posh/src/color"
"github.com/jandedobbeleer/oh-my-posh/src/runtime" "github.com/jandedobbeleer/oh-my-posh/src/log"
) )
type Wrapper struct { type Wrapper struct {
Properties Map Properties Map
Env runtime.Environment
} }
func (w *Wrapper) GetColor(property Property, defaultColor color.Ansi) color.Ansi { func (w *Wrapper) GetColor(property Property, defaultColor color.Ansi) color.Ansi {
value := w.Properties.GetColor(property, defaultColor) value := w.Properties.GetColor(property, defaultColor)
w.Env.Debug(fmt.Sprintf("%s: %s", property, value)) log.Debug(fmt.Sprintf("%s: %s", property, value))
return value return value
} }
func (w *Wrapper) GetBool(property Property, defaultValue bool) bool { func (w *Wrapper) GetBool(property Property, defaultValue bool) bool {
value := w.Properties.GetBool(property, defaultValue) value := w.Properties.GetBool(property, defaultValue)
w.Env.Debug(fmt.Sprintf("%s: %t", property, value)) log.Debug(fmt.Sprintf("%s: %t", property, value))
return value return value
} }
func (w *Wrapper) GetString(property Property, defaultValue string) string { func (w *Wrapper) GetString(property Property, defaultValue string) string {
value := w.Properties.GetString(property, defaultValue) value := w.Properties.GetString(property, defaultValue)
w.Env.Debug(value) log.Debug(value)
return value return value
} }
func (w *Wrapper) GetFloat64(property Property, defaultValue float64) float64 { func (w *Wrapper) GetFloat64(property Property, defaultValue float64) float64 {
value := w.Properties.GetFloat64(property, defaultValue) value := w.Properties.GetFloat64(property, defaultValue)
w.Env.Debug(fmt.Sprintf("%s: %f", property, value)) log.Debug(fmt.Sprintf("%s: %f", property, value))
return value return value
} }
func (w *Wrapper) GetInt(property Property, defaultValue int) int { func (w *Wrapper) GetInt(property Property, defaultValue int) int {
value := w.Properties.GetInt(property, defaultValue) value := w.Properties.GetInt(property, defaultValue)
w.Env.Debug(fmt.Sprintf("%s: %d", property, value)) log.Debug(fmt.Sprintf("%s: %d", property, value))
return value return value
} }
func (w *Wrapper) GetKeyValueMap(property Property, defaultValue map[string]string) map[string]string { func (w *Wrapper) GetKeyValueMap(property Property, defaultValue map[string]string) map[string]string {
value := w.Properties.GetKeyValueMap(property, defaultValue) value := w.Properties.GetKeyValueMap(property, defaultValue)
w.Env.Debug(fmt.Sprintf("%s: %v", property, value)) log.Debug(fmt.Sprintf("%s: %v", property, value))
return value return value
} }
func (w *Wrapper) GetStringArray(property Property, defaultValue []string) []string { func (w *Wrapper) GetStringArray(property Property, defaultValue []string) []string {
value := w.Properties.GetStringArray(property, defaultValue) value := w.Properties.GetStringArray(property, defaultValue)
w.Env.Debug(fmt.Sprintf("%s: %v", property, value)) log.Debug(fmt.Sprintf("%s: %v", property, value))
return value return value
} }
func (w *Wrapper) Get(property Property, defaultValue any) any { func (w *Wrapper) Get(property Property, defaultValue any) any {
value := w.Properties.Get(property, defaultValue) value := w.Properties.Get(property, defaultValue)
w.Env.Debug(fmt.Sprintf("%s: %v", property, value)) log.Debug(fmt.Sprintf("%s: %v", property, value))
return value return value
} }

View file

@ -1,172 +0,0 @@
package runtime
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"strconv"
"sync"
"time"
)
type Cache interface {
Init(home string)
Close()
// Gets the value for a given key.
// Returns the value and a boolean indicating if the key was found.
// In case the ttl expired, the function returns false.
Get(key string) (string, bool)
// Sets a value for a given key.
// The ttl indicates how many minutes to cache the value.
Set(key, value string, ttl int)
// Deletes a key from the cache.
Delete(key string)
}
const (
CacheFile = "/omp.cache"
)
func pid() string {
pid := os.Getenv("POSH_PID")
if len(pid) == 0 {
pid = strconv.Itoa(os.Getppid())
}
return pid
}
var (
TEMPLATECACHE = fmt.Sprintf("template_cache_%s", pid())
TOGGLECACHE = fmt.Sprintf("toggle_cache_%s", pid())
PROMPTCOUNTCACHE = fmt.Sprintf("prompt_count_cache_%s", pid())
)
type cacheObject struct {
Value string `json:"value"`
Timestamp int64 `json:"timestamp"`
TTL int `json:"ttl"`
}
func (c *cacheObject) expired() bool {
if c.TTL < 0 {
return false
}
return time.Now().Unix() >= (c.Timestamp + int64(c.TTL)*60)
}
type fileCache struct {
cache *ConcurrentMap
cachePath string
dirty bool
}
func (fc *fileCache) Init(cachePath string) {
fc.cache = NewConcurrentMap()
fc.cachePath = cachePath
cacheFilePath := filepath.Join(fc.cachePath, CacheFile)
content, err := os.ReadFile(cacheFilePath)
if err != nil {
return
}
var list map[string]*cacheObject
if err := json.Unmarshal(content, &list); err != nil {
return
}
for key, co := range list {
if co.expired() {
continue
}
fc.cache.Set(key, co)
}
}
func (fc *fileCache) Close() {
if !fc.dirty {
return
}
cache := fc.cache.SimpleMap()
if dump, err := json.MarshalIndent(cache, "", " "); err == nil {
cacheFilePath := filepath.Join(fc.cachePath, CacheFile)
_ = os.WriteFile(cacheFilePath, dump, 0644)
}
}
// returns the value for the given key as long as
// the TTL (minutes) is not expired
func (fc *fileCache) Get(key string) (string, bool) {
val, found := fc.cache.Get(key)
if !found {
return "", false
}
if co, ok := val.(*cacheObject); ok {
return co.Value, true
}
return "", false
}
// sets the value for the given key with a TTL (minutes)
func (fc *fileCache) Set(key, value string, ttl int) {
fc.cache.Set(key, &cacheObject{
Value: value,
Timestamp: time.Now().Unix(),
TTL: ttl,
})
fc.dirty = true
}
// delete the key from the cache
func (fc *fileCache) Delete(key string) {
fc.cache.Delete(key)
fc.dirty = true
}
type commandCache struct {
commands *ConcurrentMap
}
func (c *commandCache) set(command, path string) {
c.commands.Set(command, path)
}
func (c *commandCache) get(command string) (string, bool) {
cacheCommand, found := c.commands.Get(command)
if !found {
return "", false
}
command, ok := cacheCommand.(string)
return command, ok
}
type TemplateCache struct {
Root bool
PWD string
AbsolutePWD string
Folder string
Shell string
ShellVersion string
UserName string
HostName string
Code int
Env map[string]string
Var SimpleMap
OS string
WSL bool
PromptCount int
SHLVL int
Segments *ConcurrentMap
SegmentsCache SimpleMap
initialized bool
sync.RWMutex
}
func (t *TemplateCache) AddSegmentData(key string, value any) {
t.Segments.Set(key, value)
}
func (t *TemplateCache) RemoveSegmentData(key string) {
t.Segments.Delete(key)
}

View file

@ -4,14 +4,14 @@ import (
"context" "context"
"fmt" "fmt"
"io" "io"
"net/http" httplib "net/http"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
"time" "time"
"github.com/jandedobbeleer/oh-my-posh/src/log" "github.com/jandedobbeleer/oh-my-posh/src/log"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/net" "github.com/jandedobbeleer/oh-my-posh/src/runtime/http"
) )
func Download(cachePath, url string) (string, error) { func Download(cachePath, url string) (string, error) {
@ -27,13 +27,13 @@ func Download(cachePath, url string) (string, error) {
ctx, cncl := context.WithTimeout(context.Background(), time.Second*time.Duration(5)) ctx, cncl := context.WithTimeout(context.Background(), time.Second*time.Duration(5))
defer cncl() defer cncl()
request, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) request, err := httplib.NewRequestWithContext(ctx, httplib.MethodGet, url, nil)
if err != nil { if err != nil {
log.Error(err) log.Error(err)
return "", err return "", err
} }
response, err := net.HTTPClient.Do(request) response, err := http.HTTPClient.Do(request)
if err != nil { if err != nil {
log.Error(err) log.Error(err)
return "", err return "", err
@ -41,7 +41,7 @@ func Download(cachePath, url string) (string, error) {
defer response.Body.Close() defer response.Body.Close()
if response.StatusCode != http.StatusOK { if response.StatusCode != httplib.StatusOK {
err := fmt.Errorf("unexpected status code: %d", response.StatusCode) err := fmt.Errorf("unexpected status code: %d", response.StatusCode)
log.Error(err) log.Error(err)
return "", err return "", err
@ -77,13 +77,13 @@ func shouldUpdate(cachePath, url string) (string, bool) {
ctx, cncl := context.WithTimeout(context.Background(), time.Second*time.Duration(5)) ctx, cncl := context.WithTimeout(context.Background(), time.Second*time.Duration(5))
defer cncl() defer cncl()
request, err := http.NewRequestWithContext(ctx, http.MethodHead, url, nil) request, err := httplib.NewRequestWithContext(ctx, httplib.MethodHead, url, nil)
if err != nil { if err != nil {
log.Error(err) log.Error(err)
return "", true return "", true
} }
response, err := net.HTTPClient.Do(request) response, err := http.HTTPClient.Do(request)
if err != nil { if err != nil {
log.Error(err) log.Error(err)
return "", true return "", true

View file

@ -1,4 +1,4 @@
package net package http
import ( import (
"net" "net"

View file

@ -4,10 +4,7 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io" "io"
"net/http" httplib "net/http"
"github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
) )
const ( const (
@ -37,36 +34,46 @@ type OAuthRequest struct {
AccessTokenKey string AccessTokenKey string
RefreshTokenKey string RefreshTokenKey string
SegmentName string SegmentName string
RefreshToken string
AccessToken string
} }
func (o *OAuthRequest) getAccessToken() (string, error) { func (o *OAuthRequest) getAccessToken() (string, error) {
// get directly from cache // get directly from cache
if acccessToken, OK := o.env.Cache().Get(o.AccessTokenKey); OK && len(acccessToken) != 0 { if acccessToken, OK := o.Env.Cache().Get(o.AccessTokenKey); OK && len(acccessToken) != 0 {
return acccessToken, nil return acccessToken, nil
} }
// use cached refresh token to get new access token // use cached refresh token to get new access token
if refreshToken, OK := o.env.Cache().Get(o.RefreshTokenKey); OK && len(refreshToken) != 0 { if refreshToken, OK := o.Env.Cache().Get(o.RefreshTokenKey); OK && len(refreshToken) != 0 {
if acccessToken, err := o.refreshToken(refreshToken); err == nil { if acccessToken, err := o.refreshToken(refreshToken); err == nil {
return acccessToken, nil return acccessToken, nil
} }
} }
// use initial refresh token from property // use initial refresh token from property
refreshToken := o.props.GetString(properties.RefreshToken, "") // refreshToken := o.props.GetString(properties.RefreshToken, "")
// ignore an empty or default refresh token // ignore an empty or default refresh token
if len(refreshToken) == 0 || refreshToken == DefaultRefreshToken { if len(o.RefreshToken) == 0 || o.RefreshToken == DefaultRefreshToken {
return "", &OAuthError{ return "", &OAuthError{
message: InvalidRefreshToken, message: InvalidRefreshToken,
} }
} }
// no need to let the user provide access token, we'll always verify the refresh token // no need to let the user provide access token, we'll always verify the refresh token
acccessToken, err := o.refreshToken(refreshToken) acccessToken, err := o.refreshToken(o.RefreshToken)
return acccessToken, err return acccessToken, err
} }
func (o *OAuthRequest) refreshToken(refreshToken string) (string, error) { func (o *OAuthRequest) refreshToken(refreshToken string) (string, error) {
httpTimeout := o.props.GetInt(properties.HTTPTimeout, properties.DefaultHTTPTimeout) // httpTimeout := o.props.GetInt(properties.HTTPTimeout, properties.DefaultHTTPTimeout)
if o.HTTPTimeout == 0 {
o.HTTPTimeout = 20
}
url := fmt.Sprintf("https://ohmyposh.dev/api/refresh?segment=%s&token=%s", o.SegmentName, refreshToken) url := fmt.Sprintf("https://ohmyposh.dev/api/refresh?segment=%s&token=%s", o.SegmentName, refreshToken)
body, err := o.env.HTTPRequest(url, nil, httpTimeout) body, err := o.Env.HTTPRequest(url, nil, o.HTTPTimeout)
if err != nil { if err != nil {
return "", &OAuthError{ return "", &OAuthError{
// This might happen if /api was asleep. Assume the user will just retry // This might happen if /api was asleep. Assume the user will just retry
@ -81,12 +88,12 @@ func (o *OAuthRequest) refreshToken(refreshToken string) (string, error) {
} }
} }
// add tokens to cache // add tokens to cache
o.env.Cache().Set(o.AccessTokenKey, tokens.AccessToken, tokens.ExpiresIn/60) o.Env.Cache().Set(o.AccessTokenKey, tokens.AccessToken, tokens.ExpiresIn/60)
o.env.Cache().Set(o.RefreshTokenKey, tokens.RefreshToken, 2*525960) // it should never expire unless revoked, default to 2 year o.Env.Cache().Set(o.RefreshTokenKey, tokens.RefreshToken, 2*525960) // it should never expire unless revoked, default to 2 year
return tokens.AccessToken, nil return tokens.AccessToken, nil
} }
func OauthResult[a any](o *OAuthRequest, url string, body io.Reader, requestModifiers ...runtime.HTTPRequestModifier) (a, error) { func OauthResult[a any](o *OAuthRequest, url string, body io.Reader, requestModifiers ...RequestModifier) (a, error) {
if data, err := getCacheValue[a](&o.Request, url); err == nil { if data, err := getCacheValue[a](&o.Request, url); err == nil {
return data, nil return data, nil
} }
@ -98,12 +105,12 @@ func OauthResult[a any](o *OAuthRequest, url string, body io.Reader, requestModi
} }
// add token to header for authentication // add token to header for authentication
addAuthHeader := func(request *http.Request) { addAuthHeader := func(request *httplib.Request) {
request.Header.Add("Authorization", "Bearer "+accessToken) request.Header.Add("Authorization", "Bearer "+accessToken)
} }
if requestModifiers == nil { if requestModifiers == nil {
requestModifiers = []runtime.HTTPRequestModifier{} requestModifiers = []RequestModifier{}
} }
requestModifiers = append(requestModifiers, addAuthHeader) requestModifiers = append(requestModifiers, addAuthHeader)

View file

@ -4,11 +4,9 @@ import (
"fmt" "fmt"
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock" "github.com/jandedobbeleer/oh-my-posh/src/cache/mock"
"github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
mock2 "github.com/stretchr/testify/mock" testify_ "github.com/stretchr/testify/mock"
) )
type data struct { type data struct {
@ -143,32 +141,32 @@ func TestOauthResult(t *testing.T) {
url := "https://www.strava.com/api/v3/athlete/activities?page=1&per_page=1" url := "https://www.strava.com/api/v3/athlete/activities?page=1&per_page=1"
tokenURL := fmt.Sprintf("https://ohmyposh.dev/api/refresh?segment=test&token=%s", tc.RefreshToken) tokenURL := fmt.Sprintf("https://ohmyposh.dev/api/refresh?segment=test&token=%s", tc.RefreshToken)
var props properties.Map = map[properties.Property]any{ cache := &mock.Cache{}
properties.CacheTimeout: tc.CacheTimeout,
properties.AccessToken: tc.AccessToken,
properties.RefreshToken: tc.RefreshToken,
}
cache := &mock.MockedCache{}
cache.On("Get", url).Return(tc.CacheJSONResponse, !tc.ResponseCacheMiss) cache.On("Get", url).Return(tc.CacheJSONResponse, !tc.ResponseCacheMiss)
cache.On("Get", accessTokenKey).Return(tc.AccessToken, tc.AccessTokenFromCache) cache.On("Get", accessTokenKey).Return(tc.AccessToken, tc.AccessTokenFromCache)
cache.On("Get", refreshTokenKey).Return(tc.RefreshToken, tc.RefreshTokenFromCache) cache.On("Get", refreshTokenKey).Return(tc.RefreshToken, tc.RefreshTokenFromCache)
cache.On("Set", mock2.Anything, mock2.Anything, mock2.Anything) cache.On("Set", testify_.Anything, testify_.Anything, testify_.Anything)
env := &mock.MockedEnvironment{} env := &MockedEnvironment{}
env.On("Cache").Return(cache) env.On("Cache").Return(cache)
env.On("HTTPRequest", url).Return([]byte(tc.JSONResponse), tc.Error) env.On("HTTPRequest", url).Return([]byte(tc.JSONResponse), tc.Error)
env.On("HTTPRequest", tokenURL).Return([]byte(tc.TokenResponse), tc.Error) env.On("HTTPRequest", tokenURL).Return([]byte(tc.TokenResponse), tc.Error)
env.On("Error", mock2.Anything) env.On("Error", testify_.Anything)
oauth := &OAuthRequest{ oauth := &OAuthRequest{
AccessTokenKey: accessTokenKey, AccessTokenKey: accessTokenKey,
RefreshTokenKey: refreshTokenKey, RefreshTokenKey: refreshTokenKey,
SegmentName: "test", SegmentName: "test",
AccessToken: tc.AccessToken,
RefreshToken: tc.RefreshToken,
Request: Request{
Env: env,
CacheTimeout: tc.CacheTimeout,
HTTPTimeout: 20,
},
} }
oauth.Init(env, props)
got, err := OauthResult[*data](oauth, url, nil) got, err := OauthResult[*data](oauth, url, nil)
assert.Equal(t, tc.ExpectedData, got, tc.Case) assert.Equal(t, tc.ExpectedData, got, tc.Case)

View file

@ -0,0 +1,78 @@
package http
import (
"encoding/json"
"errors"
"io"
"net/http"
"github.com/jandedobbeleer/oh-my-posh/src/cache"
"github.com/jandedobbeleer/oh-my-posh/src/log"
)
type RequestModifier func(request *http.Request)
type Request struct {
Env Environment
CacheTimeout int
HTTPTimeout int
}
type Environment interface {
HTTPRequest(url string, body io.Reader, timeout int, requestModifiers ...RequestModifier) ([]byte, error)
Cache() cache.Cache
}
func Do[a any](r *Request, url string, requestModifiers ...RequestModifier) (a, error) {
if data, err := getCacheValue[a](r, url); err == nil {
return data, nil
}
return do[a](r, url, nil, requestModifiers...)
}
func getCacheValue[a any](r *Request, key string) (a, error) {
var data a
cacheTimeout := r.CacheTimeout // r.props.GetInt(properties.CacheTimeout, 30)
if cacheTimeout <= 0 {
return data, errors.New("no cache needed")
}
if val, found := r.Env.Cache().Get(key); found {
err := json.Unmarshal([]byte(val), &data)
if err != nil {
log.Error(err)
return data, err
}
return data, nil
}
err := errors.New("no data in cache")
log.Error(err)
return data, err
}
func do[a any](r *Request, url string, body io.Reader, requestModifiers ...RequestModifier) (a, error) {
var data a
httpTimeout := r.HTTPTimeout // r.props.GetInt(properties.HTTPTimeout, properties.DefaultHTTPTimeout)
responseBody, err := r.Env.HTTPRequest(url, body, httpTimeout, requestModifiers...)
if err != nil {
log.Error(err)
return data, err
}
err = json.Unmarshal(responseBody, &data)
if err != nil {
log.Error(err)
return data, err
}
cacheTimeout := r.CacheTimeout // r.props.GetInt(properties.CacheTimeout, 30)
if cacheTimeout > 0 {
r.Env.Cache().Set(url, string(responseBody), cacheTimeout)
}
return data, nil
}

View file

@ -1,16 +1,31 @@
package http package http
import ( import (
"io"
"net" "net"
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock" "github.com/jandedobbeleer/oh-my-posh/src/cache"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/cache/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
mock2 "github.com/stretchr/testify/mock" testify_ "github.com/stretchr/testify/mock"
) )
type MockedEnvironment struct {
testify_.Mock
}
func (env *MockedEnvironment) Cache() cache.Cache {
args := env.Called()
return args.Get(0).(cache.Cache)
}
func (env *MockedEnvironment) HTTPRequest(url string, _ io.Reader, _ int, _ ...RequestModifier) ([]byte, error) {
args := env.Called(url)
return args.Get(0).([]byte), args.Error(1)
}
func TestRequestResult(t *testing.T) { func TestRequestResult(t *testing.T) {
successData := &data{Hello: "world"} successData := &data{Hello: "world"}
jsonResponse := `{ "hello":"world" }` jsonResponse := `{ "hello":"world" }`
@ -62,23 +77,21 @@ func TestRequestResult(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
var props properties.Map = map[properties.Property]any{ c := &mock.Cache{}
properties.CacheTimeout: tc.CacheTimeout,
}
cache := &mock.MockedCache{} c.On("Get", url).Return(tc.CacheJSONResponse, !tc.ResponseCacheMiss)
c.On("Set", testify_.Anything, testify_.Anything, testify_.Anything)
cache.On("Get", url).Return(tc.CacheJSONResponse, !tc.ResponseCacheMiss) env := &MockedEnvironment{}
cache.On("Set", mock2.Anything, mock2.Anything, mock2.Anything)
env := &mock.MockedEnvironment{} env.On("Cache").Return(c)
env.On("Cache").Return(cache)
env.On("HTTPRequest", url).Return([]byte(tc.JSONResponse), tc.Error) env.On("HTTPRequest", url).Return([]byte(tc.JSONResponse), tc.Error)
env.On("Error", mock2.Anything).Return()
request := &Request{} request := &Request{
request.Init(env, props) Env: env,
CacheTimeout: tc.CacheTimeout,
HTTPTimeout: 0,
}
got, err := Do[*data](request, url, nil) got, err := Do[*data](request, url, nil)
assert.Equal(t, tc.ExpectedData, got, tc.Case) assert.Equal(t, tc.ExpectedData, got, tc.Case)

View file

@ -1,46 +0,0 @@
package runtime
import "sync"
func NewConcurrentMap() *ConcurrentMap {
var cm ConcurrentMap
return &cm
}
type ConcurrentMap sync.Map
func (cm *ConcurrentMap) Set(key string, value any) {
(*sync.Map)(cm).Store(key, value)
}
func (cm *ConcurrentMap) Get(key string) (any, bool) {
return (*sync.Map)(cm).Load(key)
}
func (cm *ConcurrentMap) Delete(key string) {
(*sync.Map)(cm).Delete(key)
}
func (cm *ConcurrentMap) Contains(key string) bool {
_, ok := (*sync.Map)(cm).Load(key)
return ok
}
func (cm *ConcurrentMap) SimpleMap() SimpleMap {
list := make(map[string]any)
(*sync.Map)(cm).Range(func(key, value any) bool {
list[key.(string)] = value
return true
})
return list
}
type SimpleMap map[string]any
func (m SimpleMap) ConcurrentMap() *ConcurrentMap {
var cm ConcurrentMap
for k, v := range m {
cm.Set(k, v)
}
return &cm
}

View file

@ -0,0 +1,295 @@
package mock
import (
"io"
"io/fs"
"time"
"github.com/jandedobbeleer/oh-my-posh/src/cache"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/battery"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/http"
mock "github.com/stretchr/testify/mock"
)
type Environment struct {
mock.Mock
}
func (env *Environment) Getenv(key string) string {
args := env.Called(key)
return args.String(0)
}
func (env *Environment) Pwd() string {
args := env.Called()
return args.String(0)
}
func (env *Environment) Home() string {
args := env.Called()
return args.String(0)
}
func (env *Environment) HasFiles(pattern string) bool {
args := env.Called(pattern)
return args.Bool(0)
}
func (env *Environment) HasFilesInDir(dir, pattern string) bool {
args := env.Called(dir, pattern)
return args.Bool(0)
}
func (env *Environment) HasFolder(folder string) bool {
args := env.Called(folder)
return args.Bool(0)
}
func (env *Environment) ResolveSymlink(path string) (string, error) {
args := env.Called(path)
return args.String(0), args.Error(1)
}
func (env *Environment) FileContent(file string) string {
args := env.Called(file)
return args.String(0)
}
func (env *Environment) LsDir(path string) []fs.DirEntry {
args := env.Called(path)
return args.Get(0).([]fs.DirEntry)
}
func (env *Environment) PathSeparator() string {
args := env.Called()
return args.String(0)
}
func (env *Environment) User() string {
args := env.Called()
return args.String(0)
}
func (env *Environment) Host() (string, error) {
args := env.Called()
return args.String(0), args.Error(1)
}
func (env *Environment) GOOS() string {
args := env.Called()
return args.String(0)
}
func (env *Environment) Platform() string {
args := env.Called()
return args.String(0)
}
func (env *Environment) CommandPath(command string) string {
args := env.Called(command)
return args.String(0)
}
func (env *Environment) HasCommand(command string) bool {
args := env.Called(command)
return args.Bool(0)
}
func (env *Environment) RunCommand(command string, args ...string) (string, error) {
arguments := env.Called(command, args)
return arguments.String(0), arguments.Error(1)
}
func (env *Environment) RunShellCommand(shell, command string) string {
args := env.Called(shell, command)
return args.String(0)
}
func (env *Environment) StatusCodes() (int, string) {
args := env.Called()
return args.Int(0), args.String(1)
}
func (env *Environment) ExecutionTime() float64 {
args := env.Called()
return float64(args.Int(0))
}
func (env *Environment) Root() bool {
args := env.Called()
return args.Bool(0)
}
func (env *Environment) Flags() *runtime.Flags {
arguments := env.Called()
return arguments.Get(0).(*runtime.Flags)
}
func (env *Environment) BatteryState() (*battery.Info, error) {
args := env.Called()
return args.Get(0).(*battery.Info), args.Error(1)
}
func (env *Environment) Shell() string {
args := env.Called()
return args.String(0)
}
func (env *Environment) QueryWindowTitles(processName, windowTitleRegex string) (string, error) {
args := env.Called(processName, windowTitleRegex)
return args.String(0), args.Error(1)
}
func (env *Environment) WindowsRegistryKeyValue(path string) (*runtime.WindowsRegistryValue, error) {
args := env.Called(path)
return args.Get(0).(*runtime.WindowsRegistryValue), args.Error(1)
}
func (env *Environment) HTTPRequest(url string, _ io.Reader, _ int, _ ...http.RequestModifier) ([]byte, error) {
args := env.Called(url)
return args.Get(0).([]byte), args.Error(1)
}
func (env *Environment) HasParentFilePath(path string) (*runtime.FileInfo, error) {
args := env.Called(path)
return args.Get(0).(*runtime.FileInfo), args.Error(1)
}
func (env *Environment) StackCount() int {
args := env.Called()
return args.Int(0)
}
func (env *Environment) IsWsl() bool {
args := env.Called()
return args.Bool(0)
}
func (env *Environment) IsWsl2() bool {
args := env.Called()
return args.Bool(0)
}
func (env *Environment) TerminalWidth() (int, error) {
args := env.Called()
return args.Int(0), args.Error(1)
}
func (env *Environment) CachePath() string {
args := env.Called()
return args.String(0)
}
func (env *Environment) Cache() cache.Cache {
args := env.Called()
return args.Get(0).(cache.Cache)
}
func (env *Environment) Close() {
_ = env.Called()
}
func (env *Environment) Logs() string {
args := env.Called()
return args.String(0)
}
func (env *Environment) InWSLSharedDrive() bool {
args := env.Called()
return args.Bool(0)
}
func (env *Environment) ConvertToWindowsPath(_ string) string {
args := env.Called()
return args.String(0)
}
func (env *Environment) ConvertToLinuxPath(_ string) string {
args := env.Called()
return args.String(0)
}
func (env *Environment) Connection(connectionType runtime.ConnectionType) (*runtime.Connection, error) {
args := env.Called(connectionType)
return args.Get(0).(*runtime.Connection), args.Error(1)
}
func (env *Environment) TemplateCache() *cache.Template {
args := env.Called()
return args.Get(0).(*cache.Template)
}
func (env *Environment) LoadTemplateCache() {
_ = env.Called()
}
func (env *Environment) MockGitCommand(dir, returnValue string, args ...string) {
args = append([]string{"-C", dir, "--no-optional-locks", "-c", "core.quotepath=false", "-c", "color.status=false"}, args...)
env.On("RunCommand", "git", args).Return(returnValue, nil)
}
func (env *Environment) MockHgCommand(dir, returnValue string, args ...string) {
args = append([]string{"-R", dir}, args...)
env.On("RunCommand", "hg", args).Return(returnValue, nil)
}
func (env *Environment) MockSvnCommand(dir, returnValue string, args ...string) {
args = append([]string{"-C", dir, "--no-optional-locks", "-c", "core.quotepath=false", "-c", "color.status=false"}, args...)
env.On("RunCommand", "svn", args).Return(returnValue, nil)
}
func (env *Environment) HasFileInParentDirs(pattern string, depth uint) bool {
args := env.Called(pattern, depth)
return args.Bool(0)
}
func (env *Environment) DirMatchesOneOf(dir string, regexes []string) bool {
args := env.Called(dir, regexes)
return args.Bool(0)
}
func (env *Environment) Trace(start time.Time, args ...string) {
_ = env.Called(start, args)
}
func (env *Environment) Debug(message string) {
_ = env.Called(message)
}
func (env *Environment) DebugF(format string, a ...any) {
_ = env.Called(format, a)
}
func (env *Environment) Error(err error) {
_ = env.Called(err)
}
func (env *Environment) DirIsWritable(path string) bool {
args := env.Called(path)
return args.Bool(0)
}
func (env *Environment) SetPromptCount() {
_ = env.Called()
}
func (env *Environment) CursorPosition() (int, int) {
args := env.Called()
return args.Int(0), args.Int(1)
}
func (env *Environment) SystemInfo() (*runtime.SystemInfo, error) {
args := env.Called()
return args.Get(0).(*runtime.SystemInfo), args.Error(1)
}
func (env *Environment) Unset(name string) {
for i := 0; i < len(env.ExpectedCalls); i++ {
f := env.ExpectedCalls[i]
if f.Method == name {
f.Unset()
}
}
}

View file

@ -7,7 +7,7 @@ import (
"fmt" "fmt"
"io" "io"
"io/fs" "io/fs"
"net/http" httplib "net/http"
"net/http/httputil" "net/http/httputil"
"os" "os"
"path/filepath" "path/filepath"
@ -17,12 +17,14 @@ import (
"sync" "sync"
"time" "time"
"github.com/jandedobbeleer/oh-my-posh/src/cache"
"github.com/jandedobbeleer/oh-my-posh/src/concurrent"
"github.com/jandedobbeleer/oh-my-posh/src/log" "github.com/jandedobbeleer/oh-my-posh/src/log"
"github.com/jandedobbeleer/oh-my-posh/src/regex" "github.com/jandedobbeleer/oh-my-posh/src/regex"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/battery" "github.com/jandedobbeleer/oh-my-posh/src/runtime/battery"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/cmd" "github.com/jandedobbeleer/oh-my-posh/src/runtime/cmd"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/config" "github.com/jandedobbeleer/oh-my-posh/src/runtime/config"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/net" "github.com/jandedobbeleer/oh-my-posh/src/runtime/http"
disk "github.com/shirou/gopsutil/v3/disk" disk "github.com/shirou/gopsutil/v3/disk"
load "github.com/shirou/gopsutil/v3/load" load "github.com/shirou/gopsutil/v3/load"
@ -77,8 +79,6 @@ type FileInfo struct {
IsDir bool IsDir bool
} }
type HTTPRequestModifier func(request *http.Request)
type WindowsRegistryValueType string type WindowsRegistryValueType string
const ( const (
@ -170,20 +170,20 @@ type Environment interface {
BatteryState() (*battery.Info, error) BatteryState() (*battery.Info, error)
QueryWindowTitles(processName, windowTitleRegex string) (string, error) QueryWindowTitles(processName, windowTitleRegex string) (string, error)
WindowsRegistryKeyValue(path string) (*WindowsRegistryValue, error) WindowsRegistryKeyValue(path string) (*WindowsRegistryValue, error)
HTTPRequest(url string, body io.Reader, timeout int, requestModifiers ...HTTPRequestModifier) ([]byte, error) HTTPRequest(url string, body io.Reader, timeout int, requestModifiers ...http.RequestModifier) ([]byte, error)
IsWsl() bool IsWsl() bool
IsWsl2() bool IsWsl2() bool
StackCount() int StackCount() int
TerminalWidth() (int, error) TerminalWidth() (int, error)
CachePath() string CachePath() string
Cache() Cache Cache() cache.Cache
Close() Close()
Logs() string Logs() string
InWSLSharedDrive() bool InWSLSharedDrive() bool
ConvertToLinuxPath(path string) string ConvertToLinuxPath(path string) string
ConvertToWindowsPath(path string) string ConvertToWindowsPath(path string) string
Connection(connectionType ConnectionType) (*Connection, error) Connection(connectionType ConnectionType) (*Connection, error)
TemplateCache() *TemplateCache TemplateCache() *cache.Template
LoadTemplateCache() LoadTemplateCache()
SetPromptCount() SetPromptCount()
CursorPosition() (row, col int) CursorPosition() (row, col int)
@ -196,18 +196,18 @@ type Environment interface {
type Terminal struct { type Terminal struct {
CmdFlags *Flags CmdFlags *Flags
Var SimpleMap Var concurrent.SimpleMap
cwd string cwd string
host string host string
cmdCache *commandCache cmdCache *cache.Command
fileCache *fileCache fileCache *cache.File
tmplCache *TemplateCache tmplCache *cache.Template
networks []*Connection networks []*Connection
sync.RWMutex sync.RWMutex
lsDirMap ConcurrentMap lsDirMap concurrent.Map
} }
func (term *Terminal) Init() { func (term *Terminal) Init() {
@ -224,14 +224,14 @@ func (term *Terminal) Init() {
log.Plain() log.Plain()
} }
term.fileCache = &fileCache{} term.fileCache = &cache.File{}
term.fileCache.Init(term.CachePath()) term.fileCache.Init(term.CachePath())
term.resolveConfigPath() term.resolveConfigPath()
term.cmdCache = &commandCache{ term.cmdCache = &cache.Command{
commands: NewConcurrentMap(), Commands: concurrent.NewMap(),
} }
term.tmplCache = &TemplateCache{} term.tmplCache = &cache.Template{}
term.SetPromptCount() term.SetPromptCount()
} }
@ -501,7 +501,7 @@ func (term *Terminal) GOOS() string {
func (term *Terminal) RunCommand(command string, args ...string) (string, error) { func (term *Terminal) RunCommand(command string, args ...string) (string, error) {
defer term.Trace(time.Now(), append([]string{command}, args...)...) defer term.Trace(time.Now(), append([]string{command}, args...)...)
if cacheCommand, ok := term.cmdCache.get(command); ok { if cacheCommand, ok := term.cmdCache.Get(command); ok {
command = cacheCommand command = cacheCommand
} }
output, err := cmd.Run(command, args...) output, err := cmd.Run(command, args...)
@ -522,14 +522,14 @@ func (term *Terminal) RunShellCommand(shell, command string) string {
func (term *Terminal) CommandPath(command string) string { func (term *Terminal) CommandPath(command string) string {
defer term.Trace(time.Now(), command) defer term.Trace(time.Now(), command)
if path, ok := term.cmdCache.get(command); ok { if path, ok := term.cmdCache.Get(command); ok {
term.Debug(path) term.Debug(path)
return path return path
} }
path, err := term.LookPath(command) path, err := term.LookPath(command)
if err == nil { if err == nil {
term.cmdCache.set(command, path) term.cmdCache.Set(command, path)
term.Debug(path) term.Debug(path)
return path return path
} }
@ -617,13 +617,13 @@ func (term *Terminal) unWrapError(err error) error {
return cause return cause
} }
func (term *Terminal) HTTPRequest(targetURL string, body io.Reader, timeout int, requestModifiers ...HTTPRequestModifier) ([]byte, error) { func (term *Terminal) HTTPRequest(targetURL string, body io.Reader, timeout int, requestModifiers ...http.RequestModifier) ([]byte, error) {
defer term.Trace(time.Now(), targetURL) defer term.Trace(time.Now(), targetURL)
ctx, cncl := context.WithTimeout(context.Background(), time.Millisecond*time.Duration(timeout)) ctx, cncl := context.WithTimeout(context.Background(), time.Millisecond*time.Duration(timeout))
defer cncl() defer cncl()
request, err := http.NewRequestWithContext(ctx, http.MethodGet, targetURL, body) request, err := httplib.NewRequestWithContext(ctx, httplib.MethodGet, targetURL, body)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -637,7 +637,7 @@ func (term *Terminal) HTTPRequest(targetURL string, body io.Reader, timeout int,
term.Debug(string(dump)) term.Debug(string(dump))
} }
response, err := net.HTTPClient.Do(request) response, err := http.HTTPClient.Do(request)
if err != nil { if err != nil {
term.Error(err) term.Error(err)
return nil, term.unWrapError(err) return nil, term.unWrapError(err)
@ -697,7 +697,7 @@ func (term *Terminal) StackCount() int {
return term.CmdFlags.StackCount return term.CmdFlags.StackCount
} }
func (term *Terminal) Cache() Cache { func (term *Terminal) Cache() cache.Cache {
return term.fileCache return term.fileCache
} }
@ -708,11 +708,13 @@ func (term *Terminal) saveTemplateCache() {
if !canSave { if !canSave {
return return
} }
cache := term.TemplateCache()
cache.SegmentsCache = cache.Segments.SimpleMap() tmplCache := term.TemplateCache()
templateCache, err := json.Marshal(cache) tmplCache.SegmentsCache = tmplCache.Segments.ToSimpleMap()
templateCache, err := json.Marshal(tmplCache)
if err == nil { if err == nil {
term.fileCache.Set(TEMPLATECACHE, string(templateCache), 1440) term.fileCache.Set(cache.TEMPLATECACHE, string(templateCache), 1440)
} }
} }
@ -724,18 +726,23 @@ func (term *Terminal) Close() {
func (term *Terminal) LoadTemplateCache() { func (term *Terminal) LoadTemplateCache() {
defer term.Trace(time.Now()) defer term.Trace(time.Now())
val, OK := term.fileCache.Get(TEMPLATECACHE)
val, OK := term.fileCache.Get(cache.TEMPLATECACHE)
if !OK { if !OK {
return return
} }
var tmplCache TemplateCache
var tmplCache cache.Template
err := json.Unmarshal([]byte(val), &tmplCache) err := json.Unmarshal([]byte(val), &tmplCache)
if err != nil { if err != nil {
term.Error(err) term.Error(err)
return return
} }
tmplCache.Segments = tmplCache.SegmentsCache.ConcurrentMap() tmplCache.Segments = tmplCache.SegmentsCache.ConcurrentMap()
tmplCache.initialized = true tmplCache.Initialized = true
term.tmplCache = &tmplCache term.tmplCache = &tmplCache
} }
@ -743,13 +750,13 @@ func (term *Terminal) Logs() string {
return log.String() return log.String()
} }
func (term *Terminal) TemplateCache() *TemplateCache { func (term *Terminal) TemplateCache() *cache.Template {
defer term.Trace(time.Now()) defer term.Trace(time.Now())
tmplCache := term.tmplCache tmplCache := term.tmplCache
tmplCache.Lock() tmplCache.Lock()
defer tmplCache.Unlock() defer tmplCache.Unlock()
if tmplCache.initialized { if tmplCache.Initialized {
return tmplCache return tmplCache
} }
@ -758,7 +765,7 @@ func (term *Terminal) TemplateCache() *TemplateCache {
tmplCache.ShellVersion = term.CmdFlags.ShellVersion tmplCache.ShellVersion = term.CmdFlags.ShellVersion
tmplCache.Code, _ = term.StatusCodes() tmplCache.Code, _ = term.StatusCodes()
tmplCache.WSL = term.IsWsl() tmplCache.WSL = term.IsWsl()
tmplCache.Segments = NewConcurrentMap() tmplCache.Segments = concurrent.NewMap()
tmplCache.PromptCount = term.CmdFlags.PromptCount tmplCache.PromptCount = term.CmdFlags.PromptCount
tmplCache.Env = make(map[string]string) tmplCache.Env = make(map[string]string)
tmplCache.Var = make(map[string]any) tmplCache.Var = make(map[string]any)
@ -807,7 +814,7 @@ func (term *Terminal) TemplateCache() *TemplateCache {
tmplCache.SHLVL = shlvl tmplCache.SHLVL = shlvl
} }
tmplCache.initialized = true tmplCache.Initialized = true
return tmplCache return tmplCache
} }
@ -863,13 +870,13 @@ func (term *Terminal) SetPromptCount() {
} }
} }
var count int var count int
if val, found := term.Cache().Get(PROMPTCOUNTCACHE); found { if val, found := term.Cache().Get(cache.PROMPTCOUNTCACHE); found {
count, _ = strconv.Atoi(val) count, _ = strconv.Atoi(val)
} }
// only write to cache if we're the primary prompt // only write to cache if we're the primary prompt
if term.CmdFlags.Primary { if term.CmdFlags.Primary {
count++ count++
term.Cache().Set(PROMPTCOUNTCACHE, strconv.Itoa(count), 1440) term.Cache().Set(cache.PROMPTCOUNTCACHE, strconv.Itoa(count), 1440)
} }
term.CmdFlags.PromptCount = count term.CmdFlags.PromptCount = count
} }

View file

@ -5,10 +5,10 @@ import (
"path" "path"
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
mock2 "github.com/stretchr/testify/mock" testify_ "github.com/stretchr/testify/mock"
) )
const ( const (
@ -32,7 +32,7 @@ func TestArgocdGetConfigFromOpts(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("Getenv", argocdOptsEnv).Return(tc.Opts) env.On("Getenv", argocdOptsEnv).Return(tc.Opts)
argocd := &Argocd{ argocd := &Argocd{
@ -57,7 +57,7 @@ func TestArgocdGetConfigPath(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("Home").Return(poshHome) env.On("Home").Return(poshHome)
env.On("Getenv", argocdOptsEnv).Return(tc.Opts) env.On("Getenv", argocdOptsEnv).Return(tc.Opts)
@ -153,9 +153,9 @@ users:
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("FileContent", configFile).Return(tc.Config) env.On("FileContent", configFile).Return(tc.Config)
env.On("Error", mock2.Anything).Return() env.On("Error", testify_.Anything).Return()
argocd := &Argocd{ argocd := &Argocd{
env: env, env: env,
@ -246,11 +246,11 @@ servers:
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("Home").Return(poshHome) env.On("Home").Return(poshHome)
env.On("Getenv", argocdOptsEnv).Return(tc.Opts) env.On("Getenv", argocdOptsEnv).Return(tc.Opts)
env.On("FileContent", configFile).Return(tc.Config) env.On("FileContent", configFile).Return(tc.Config)
env.On("Error", mock2.Anything).Return() env.On("Error", testify_.Anything).Return()
argocd := &Argocd{ argocd := &Argocd{
env: env, env: env,

View file

@ -3,8 +3,8 @@ package segments
import ( import (
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -51,7 +51,7 @@ func TestAWSSegment(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("Getenv", "AWS_VAULT").Return(tc.Vault) env.On("Getenv", "AWS_VAULT").Return(tc.Vault)
env.On("Getenv", "AWS_PROFILE").Return(tc.Profile) env.On("Getenv", "AWS_PROFILE").Return(tc.Profile)
env.On("Getenv", "AWS_DEFAULT_PROFILE").Return(tc.DefaultProfile) env.On("Getenv", "AWS_DEFAULT_PROFILE").Return(tc.DefaultProfile)

View file

@ -5,9 +5,9 @@ import (
"path/filepath" "path/filepath"
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime" "github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -108,7 +108,7 @@ func TestAzSegment(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("Home").Return(poshHome) env.On("Home").Return(poshHome)
var azureProfile, azureRmContext string var azureProfile, azureRmContext string

View file

@ -6,11 +6,11 @@ import (
"path/filepath" "path/filepath"
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime" "github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
mock2 "github.com/stretchr/testify/mock" testify_ "github.com/stretchr/testify/mock"
) )
func TestAzdSegment(t *testing.T) { func TestAzdSegment(t *testing.T) {
@ -35,8 +35,8 @@ func TestAzdSegment(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("Debug", mock2.Anything) env.On("Debug", testify_.Anything)
if tc.IsInited { if tc.IsInited {
fileInfo := &runtime.FileInfo{ fileInfo := &runtime.FileInfo{

View file

@ -5,8 +5,9 @@ import (
"testing" "testing"
"time" "time"
"github.com/jandedobbeleer/oh-my-posh/src/mock" cache_ "github.com/jandedobbeleer/oh-my-posh/src/cache/mock"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -144,7 +145,7 @@ func TestBrewfatherSegment(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := &mock.MockedEnvironment{} env := &mock.Environment{}
props := properties.Map{ props := properties.Map{
properties.CacheTimeout: tc.CacheTimeout, properties.CacheTimeout: tc.CacheTimeout,
BFBatchID: BFFakeBatchID, BFBatchID: BFFakeBatchID,
@ -152,7 +153,7 @@ func TestBrewfatherSegment(t *testing.T) {
BFUserID: "FAKE", BFUserID: "FAKE",
} }
cache := &mock.MockedCache{} cache := &cache_.Cache{}
cache.On("Get", BFCacheKey).Return(nil, false) // cache testing later because cache is a little more complicated than just the single response. cache.On("Get", BFCacheKey).Return(nil, false) // cache testing later because cache is a little more complicated than just the single response.
// cache.On("Set", BFCacheKey, tc.JSONResponse, tc.CacheTimeout).Return() // cache.On("Set", BFCacheKey, tc.JSONResponse, tc.CacheTimeout).Return()

View file

@ -5,11 +5,12 @@ import (
"fmt" "fmt"
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock" cache_ "github.com/jandedobbeleer/oh-my-posh/src/cache/mock"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
mock2 "github.com/stretchr/testify/mock" testify_ "github.com/stretchr/testify/mock"
) )
const ( const (
@ -201,7 +202,7 @@ func TestCarbonIntensitySegmentSingle(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := &mock.MockedEnvironment{} env := &mock.Environment{}
var props = properties.Map{ var props = properties.Map{
properties.HTTPTimeout: 5000, properties.HTTPTimeout: 5000,
properties.CacheTimeout: 0, properties.CacheTimeout: 0,
@ -226,7 +227,7 @@ func TestCarbonIntensitySegmentSingle(t *testing.T) {
} }
env.On("HTTPRequest", CARBONINTENSITYURL).Return([]byte(jsonResponse), responseError) env.On("HTTPRequest", CARBONINTENSITYURL).Return([]byte(jsonResponse), responseError)
env.On("Error", mock2.Anything) env.On("Error", testify_.Anything)
d := &CarbonIntensity{ d := &CarbonIntensity{
props: props, props: props,
@ -250,13 +251,14 @@ func TestCarbonIntensitySegmentFromCache(t *testing.T) {
response := `{ "data": [ { "from": "2023-10-27T12:30Z", "to": "2023-10-27T13:00Z", "intensity": { "forecast": 199, "actual": 193, "index": "moderate" } } ] }` response := `{ "data": [ { "from": "2023-10-27T12:30Z", "to": "2023-10-27T13:00Z", "intensity": { "forecast": 199, "actual": 193, "index": "moderate" } } ] }`
expectedString := "CO₂ •193 ↗ 199" expectedString := "CO₂ •193 ↗ 199"
env := &mock.MockedEnvironment{} env := &mock.Environment{}
cache := &mock.MockedCache{} cache := &cache_.Cache{}
d := &CarbonIntensity{ d := &CarbonIntensity{
props: properties.Map{}, props: properties.Map{},
env: env, env: env,
} }
cache.On("Get", CARBONINTENSITYURL).Return(response, true) cache.On("Get", CARBONINTENSITYURL).Return(response, true)
cache.On("Set").Return() cache.On("Set").Return()
env.On("Cache").Return(cache) env.On("Cache").Return(cache)

View file

@ -6,9 +6,9 @@ import (
"os/exec" "os/exec"
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime" "github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -64,7 +64,7 @@ func TestCFTargetSegment(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
var env = new(mock.MockedEnvironment) var env = new(mock.Environment)
env.On("HasCommand", "cf").Return(true) env.On("HasCommand", "cf").Return(true)
env.On("RunCommand", "cf", []string{"target"}).Return(tc.TargetOutput, tc.CommandError) env.On("RunCommand", "cf", []string{"target"}).Return(tc.TargetOutput, tc.CommandError)
env.On("Pwd", nil).Return("/usr/home/dev/my-app") env.On("Pwd", nil).Return("/usr/home/dev/my-app")

View file

@ -3,14 +3,14 @@ package segments
import ( import (
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
func TestExecuteCommand(t *testing.T) { func TestExecuteCommand(t *testing.T) {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("HasCommand", "bash").Return(true) env.On("HasCommand", "bash").Return(true)
env.On("RunShellCommand", "bash", "echo hello").Return("hello") env.On("RunShellCommand", "bash", "echo hello").Return("hello")
props := properties.Map{ props := properties.Map{
@ -26,7 +26,7 @@ func TestExecuteCommand(t *testing.T) {
} }
func TestExecuteMultipleCommandsOrFirst(t *testing.T) { func TestExecuteMultipleCommandsOrFirst(t *testing.T) {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("HasCommand", "bash").Return(true) env.On("HasCommand", "bash").Return(true)
env.On("RunShellCommand", "bash", "exit 1").Return("") env.On("RunShellCommand", "bash", "exit 1").Return("")
env.On("RunShellCommand", "bash", "echo hello").Return("hello") env.On("RunShellCommand", "bash", "echo hello").Return("hello")
@ -44,7 +44,7 @@ func TestExecuteMultipleCommandsOrFirst(t *testing.T) {
} }
func TestExecuteMultipleCommandsOrSecond(t *testing.T) { func TestExecuteMultipleCommandsOrSecond(t *testing.T) {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("HasCommand", "bash").Return(true) env.On("HasCommand", "bash").Return(true)
env.On("RunShellCommand", "bash", "echo hello").Return("hello") env.On("RunShellCommand", "bash", "echo hello").Return("hello")
env.On("RunShellCommand", "bash", "echo world").Return("world") env.On("RunShellCommand", "bash", "echo world").Return("world")
@ -61,7 +61,7 @@ func TestExecuteMultipleCommandsOrSecond(t *testing.T) {
} }
func TestExecuteMultipleCommandsAnd(t *testing.T) { func TestExecuteMultipleCommandsAnd(t *testing.T) {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("HasCommand", "bash").Return(true) env.On("HasCommand", "bash").Return(true)
env.On("RunShellCommand", "bash", "echo hello").Return("hello") env.On("RunShellCommand", "bash", "echo hello").Return("hello")
env.On("RunShellCommand", "bash", "echo world").Return("world") env.On("RunShellCommand", "bash", "echo world").Return("world")
@ -78,7 +78,7 @@ func TestExecuteMultipleCommandsAnd(t *testing.T) {
} }
func TestExecuteSingleCommandEmpty(t *testing.T) { func TestExecuteSingleCommandEmpty(t *testing.T) {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("HasCommand", "bash").Return(true) env.On("HasCommand", "bash").Return(true)
env.On("RunShellCommand", "bash", "").Return("") env.On("RunShellCommand", "bash", "").Return("")
props := properties.Map{ props := properties.Map{
@ -93,7 +93,7 @@ func TestExecuteSingleCommandEmpty(t *testing.T) {
} }
func TestExecuteSingleCommandNoCommandProperty(t *testing.T) { func TestExecuteSingleCommandNoCommandProperty(t *testing.T) {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("HasCommand", "bash").Return(true) env.On("HasCommand", "bash").Return(true)
env.On("RunShellCommand", "bash", "").Return("") env.On("RunShellCommand", "bash", "").Return("")
var props properties.Map var props properties.Map
@ -106,7 +106,7 @@ func TestExecuteSingleCommandNoCommandProperty(t *testing.T) {
} }
func TestExecuteMultipleCommandsAndDisabled(t *testing.T) { func TestExecuteMultipleCommandsAndDisabled(t *testing.T) {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("HasCommand", "bash").Return(true) env.On("HasCommand", "bash").Return(true)
env.On("RunShellCommand", "bash", "echo").Return("") env.On("RunShellCommand", "bash", "echo").Return("")
props := properties.Map{ props := properties.Map{
@ -121,7 +121,7 @@ func TestExecuteMultipleCommandsAndDisabled(t *testing.T) {
} }
func TestExecuteMultipleCommandsOrDisabled(t *testing.T) { func TestExecuteMultipleCommandsOrDisabled(t *testing.T) {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("HasCommand", "bash").Return(true) env.On("HasCommand", "bash").Return(true)
env.On("RunShellCommand", "bash", "echo").Return("") env.On("RunShellCommand", "bash", "echo").Return("")
env.On("RunShellCommand", "bash", "echo|| echo").Return("") env.On("RunShellCommand", "bash", "echo|| echo").Return("")
@ -137,7 +137,7 @@ func TestExecuteMultipleCommandsOrDisabled(t *testing.T) {
} }
func TestExecuteNonInterpretedCommand(t *testing.T) { func TestExecuteNonInterpretedCommand(t *testing.T) {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("HasCommand", "bash").Return(true) env.On("HasCommand", "bash").Return(true)
env.On("RunShellCommand", "bash", "echo hello && echo world").Return("hello world") env.On("RunShellCommand", "bash", "echo hello && echo world").Return("hello world")
props := properties.Map{ props := properties.Map{
@ -174,7 +174,7 @@ func TestExecuteScript(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
script := "../test/script.sh" script := "../test/script.sh"
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("HasCommand", "bash").Return(true) env.On("HasCommand", "bash").Return(true)
env.On("RunShellCommand", "bash", script).Return(tc.Output) env.On("RunShellCommand", "bash", script).Return(tc.Output)
props := properties.Map{ props := properties.Map{

View file

@ -4,9 +4,9 @@ import (
"fmt" "fmt"
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime" "github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -88,7 +88,7 @@ func TestConnection(t *testing.T) {
}, },
} }
for _, tc := range cases { for _, tc := range cases {
env := &mock.MockedEnvironment{} env := &mock.Environment{}
for _, con := range tc.Connections { for _, con := range tc.Connections {
env.On("Connection", con.Connection.Type).Return(con.Connection, con.Error) env.On("Connection", con.Connection.Type).Return(con.Connection, con.Error)
} }

View file

@ -3,8 +3,8 @@ package segments
import ( import (
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -34,7 +34,7 @@ func TestDockerSegment(t *testing.T) {
for _, tc := range cases { for _, tc := range cases {
docker := &Docker{} docker := &Docker{}
env := new(mock.MockedEnvironment) env := new(mock.Environment)
docker.Init(properties.Map{}, env) docker.Init(properties.Map{}, env)
for _, v := range docker.envVars() { for _, v := range docker.envVars() {

View file

@ -5,14 +5,14 @@ import (
"testing" "testing"
"time" "time"
"github.com/jandedobbeleer/oh-my-posh/src/mock"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
func TestExecutionTimeWriterDefaultThresholdEnabled(t *testing.T) { func TestExecutionTimeWriterDefaultThresholdEnabled(t *testing.T) {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("ExecutionTime").Return(1337) env.On("ExecutionTime").Return(1337)
executionTime := &Executiontime{ executionTime := &Executiontime{
env: env, env: env,
@ -22,7 +22,7 @@ func TestExecutionTimeWriterDefaultThresholdEnabled(t *testing.T) {
} }
func TestExecutionTimeWriterDefaultThresholdDisabled(t *testing.T) { func TestExecutionTimeWriterDefaultThresholdDisabled(t *testing.T) {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("ExecutionTime").Return(1) env.On("ExecutionTime").Return(1)
executionTime := &Executiontime{ executionTime := &Executiontime{
env: env, env: env,
@ -32,7 +32,7 @@ func TestExecutionTimeWriterDefaultThresholdDisabled(t *testing.T) {
} }
func TestExecutionTimeWriterCustomThresholdEnabled(t *testing.T) { func TestExecutionTimeWriterCustomThresholdEnabled(t *testing.T) {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("ExecutionTime").Return(99) env.On("ExecutionTime").Return(99)
props := properties.Map{ props := properties.Map{
ThresholdProperty: float64(10), ThresholdProperty: float64(10),
@ -45,7 +45,7 @@ func TestExecutionTimeWriterCustomThresholdEnabled(t *testing.T) {
} }
func TestExecutionTimeWriterCustomThresholdDisabled(t *testing.T) { func TestExecutionTimeWriterCustomThresholdDisabled(t *testing.T) {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("ExecutionTime").Return(99) env.On("ExecutionTime").Return(99)
props := properties.Map{ props := properties.Map{
ThresholdProperty: float64(100), ThresholdProperty: float64(100),
@ -60,7 +60,7 @@ func TestExecutionTimeWriterCustomThresholdDisabled(t *testing.T) {
func TestExecutionTimeWriterDuration(t *testing.T) { func TestExecutionTimeWriterDuration(t *testing.T) {
input := 1337 input := 1337
expected := "1.337s" expected := "1.337s"
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("ExecutionTime").Return(input) env.On("ExecutionTime").Return(input)
executionTime := &Executiontime{ executionTime := &Executiontime{
env: env, env: env,
@ -73,7 +73,7 @@ func TestExecutionTimeWriterDuration(t *testing.T) {
func TestExecutionTimeWriterDuration2(t *testing.T) { func TestExecutionTimeWriterDuration2(t *testing.T) {
input := 13371337 input := 13371337
expected := "3h 42m 51.337s" expected := "3h 42m 51.337s"
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("ExecutionTime").Return(input) env.On("ExecutionTime").Return(input)
executionTime := &Executiontime{ executionTime := &Executiontime{
env: env, env: env,

View file

@ -4,9 +4,9 @@ import (
"path/filepath" "path/filepath"
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock" "github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
mock2 "github.com/stretchr/testify/mock" testify_ "github.com/stretchr/testify/mock"
) )
func TestFirebaseSegment(t *testing.T) { func TestFirebaseSegment(t *testing.T) {
@ -53,12 +53,12 @@ func TestFirebaseSegment(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("Home").Return("home") env.On("Home").Return("home")
env.On("Pwd").Return(tc.ActivePath) env.On("Pwd").Return(tc.ActivePath)
fcPath := filepath.Join("home", ".config", "configstore", "firebase-tools.json") fcPath := filepath.Join("home", ".config", "configstore", "firebase-tools.json")
env.On("FileContent", fcPath).Return(tc.ActiveConfig) env.On("FileContent", fcPath).Return(tc.ActiveConfig)
env.On("Error", mock2.Anything).Return() env.On("Error", testify_.Anything).Return()
f := Firebase{ f := Firebase{
env: env, env: env,
} }
@ -96,12 +96,12 @@ func TestGetFirebaseActiveConfig(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("Home").Return("home") env.On("Home").Return("home")
configPath := filepath.Join("home", ".config", "configstore") configPath := filepath.Join("home", ".config", "configstore")
contentPath := filepath.Join(configPath, "firebase-tools.json") contentPath := filepath.Join(configPath, "firebase-tools.json")
env.On("FileContent", contentPath).Return(tc.ActiveConfig) env.On("FileContent", contentPath).Return(tc.ActiveConfig)
env.On("Error", mock2.Anything).Return() env.On("Error", testify_.Anything).Return()
f := Firebase{ f := Firebase{
env: env, env: env,
} }

View file

@ -5,8 +5,8 @@ import (
"strings" "strings"
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -52,7 +52,7 @@ func TestFossilStatus(t *testing.T) {
}, },
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("GOOS").Return("unix") env.On("GOOS").Return("unix")
env.On("IsWsl").Return(false) env.On("IsWsl").Return(false)
env.On("InWSLSharedDrive").Return(false) env.On("InWSLSharedDrive").Return(false)

View file

@ -4,11 +4,11 @@ import (
"path" "path"
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock"
"github.com/jandedobbeleer/oh-my-posh/src/runtime" "github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
mock2 "github.com/stretchr/testify/mock" testify_ "github.com/stretchr/testify/mock"
) )
func TestGcpSegment(t *testing.T) { func TestGcpSegment(t *testing.T) {
@ -51,13 +51,13 @@ func TestGcpSegment(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("Getenv", "CLOUDSDK_CONFIG").Return("config") env.On("Getenv", "CLOUDSDK_CONFIG").Return("config")
fcPath := path.Join("config", "active_config") fcPath := path.Join("config", "active_config")
env.On("FileContent", fcPath).Return(tc.ActiveConfig) env.On("FileContent", fcPath).Return(tc.ActiveConfig)
cfgpath := path.Join("config", "configurations", "config_production") cfgpath := path.Join("config", "configurations", "config_production")
env.On("FileContent", cfgpath).Return(tc.CfgData) env.On("FileContent", cfgpath).Return(tc.CfgData)
env.On("Error", mock2.Anything).Return() env.On("Error", testify_.Anything).Return()
g := &Gcp{ g := &Gcp{
env: env, env: env,
} }
@ -96,7 +96,7 @@ func TestGetConfigDirectory(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("Getenv", "CLOUDSDK_CONFIG").Return(tc.CloudSDKConfig) env.On("Getenv", "CLOUDSDK_CONFIG").Return(tc.CloudSDKConfig)
env.On("Getenv", "APPDATA").Return(tc.AppData) env.On("Getenv", "APPDATA").Return(tc.AppData)
env.On("Home").Return(tc.Home) env.On("Home").Return(tc.Home)
@ -127,7 +127,7 @@ func TestGetActiveConfig(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("FileContent", "active_config").Return(tc.ActiveConfig) env.On("FileContent", "active_config").Return(tc.ActiveConfig)
g := &Gcp{ g := &Gcp{
env: env, env: env,

View file

@ -9,12 +9,12 @@ import (
"testing" "testing"
"time" "time"
"github.com/jandedobbeleer/oh-my-posh/src/mock"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime" "github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
mock2 "github.com/stretchr/testify/mock" testify_ "github.com/stretchr/testify/mock"
) )
const ( const (
@ -24,7 +24,7 @@ const (
) )
func TestEnabledGitNotFound(t *testing.T) { func TestEnabledGitNotFound(t *testing.T) {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("InWSLSharedDrive").Return(false) env.On("InWSLSharedDrive").Return(false)
env.On("HasCommand", "git").Return(false) env.On("HasCommand", "git").Return(false)
env.On("GOOS").Return("") env.On("GOOS").Return("")
@ -44,7 +44,7 @@ func TestEnabledInWorkingDirectory(t *testing.T) {
ParentFolder: "/dir", ParentFolder: "/dir",
IsDir: true, IsDir: true,
} }
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("InWSLSharedDrive").Return(false) env.On("InWSLSharedDrive").Return(false)
env.On("HasCommand", "git").Return(true) env.On("HasCommand", "git").Return(true)
env.On("GOOS").Return("") env.On("GOOS").Return("")
@ -55,7 +55,7 @@ func TestEnabledInWorkingDirectory(t *testing.T) {
env.On("PathSeparator").Return("/") env.On("PathSeparator").Return("/")
env.On("Home").Return(poshHome) env.On("Home").Return(poshHome)
env.On("Getenv", poshGitEnv).Return("") env.On("Getenv", poshGitEnv).Return("")
env.On("DirMatchesOneOf", mock2.Anything, mock2.Anything).Return(false) env.On("DirMatchesOneOf", testify_.Anything, testify_.Anything).Return(false)
g := &Git{ g := &Git{
scm: scm{ scm: scm{
env: env, env: env,
@ -132,7 +132,7 @@ func TestEnabledInWorktree(t *testing.T) {
ParentFolder: TestRootPath + "dev", ParentFolder: TestRootPath + "dev",
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("FileContent", TestRootPath+dotGit).Return(fmt.Sprintf("gitdir: %s", tc.WorkingFolder)) env.On("FileContent", TestRootPath+dotGit).Return(fmt.Sprintf("gitdir: %s", tc.WorkingFolder))
env.On("FileContent", filepath.Join(tc.WorkingFolder, tc.WorkingFolderAddon)).Return(tc.WorkingFolderContent) env.On("FileContent", filepath.Join(tc.WorkingFolder, tc.WorkingFolderAddon)).Return(tc.WorkingFolderContent)
env.On("HasFilesInDir", tc.WorkingFolder, tc.WorkingFolderAddon).Return(true) env.On("HasFilesInDir", tc.WorkingFolder, tc.WorkingFolderAddon).Return(true)
@ -188,7 +188,7 @@ func TestEnabledInBareRepo(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
pwd := "/home/user/bare.git" pwd := "/home/user/bare.git"
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("InWSLSharedDrive").Return(false) env.On("InWSLSharedDrive").Return(false)
env.On("GOOS").Return("") env.On("GOOS").Return("")
env.On("HasCommand", "git").Return(true) env.On("HasCommand", "git").Return(true)
@ -217,7 +217,7 @@ func TestGetGitOutputForCommand(t *testing.T) {
args := []string{"-C", "", "--no-optional-locks", "-c", "core.quotepath=false", "-c", "color.status=false"} args := []string{"-C", "", "--no-optional-locks", "-c", "core.quotepath=false", "-c", "color.status=false"}
commandArgs := []string{"symbolic-ref", "--short", "HEAD"} commandArgs := []string{"symbolic-ref", "--short", "HEAD"}
want := "je suis le output" want := "je suis le output"
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("IsWsl").Return(false) env.On("IsWsl").Return(false)
env.On("RunCommand", "git", append(args, commandArgs...)).Return(want, nil) env.On("RunCommand", "git", append(args, commandArgs...)).Return(want, nil)
env.On("GOOS").Return("unix") env.On("GOOS").Return("unix")
@ -335,7 +335,7 @@ func TestSetGitHEADContextClean(t *testing.T) {
}, },
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("InWSLSharedDrive").Return(false) env.On("InWSLSharedDrive").Return(false)
env.On("GOOS").Return("unix") env.On("GOOS").Return("unix")
env.On("IsWsl").Return(false) env.On("IsWsl").Return(false)
@ -404,7 +404,7 @@ func TestSetPrettyHEADName(t *testing.T) {
{Case: "no hash on commit", Expected: "commit 1234567", HEAD: "12345678910"}, {Case: "no hash on commit", Expected: "commit 1234567", HEAD: "12345678910"},
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("FileContent", "/HEAD").Return(tc.HEAD) env.On("FileContent", "/HEAD").Return(tc.HEAD)
env.On("GOOS").Return("unix") env.On("GOOS").Return("unix")
env.On("IsWsl").Return(false) env.On("IsWsl").Return(false)
@ -575,7 +575,7 @@ func TestSetGitStatus(t *testing.T) {
}, },
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("GOOS").Return("unix") env.On("GOOS").Return("unix")
env.On("IsWsl").Return(false) env.On("IsWsl").Return(false)
env.MockGitCommand("", strings.ReplaceAll(tc.Output, "\t", ""), "status", "-unormal", "--branch", "--porcelain=2") env.MockGitCommand("", strings.ReplaceAll(tc.Output, "\t", ""), "status", "-unormal", "--branch", "--porcelain=2")
@ -618,7 +618,7 @@ func TestGetStashContextZeroEntries(t *testing.T) {
{Expected: 4, StashContent: "1\n2\n3\n4\n\n"}, {Expected: 4, StashContent: "1\n2\n3\n4\n\n"},
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("FileContent", "/logs/refs/stash").Return(tc.StashContent) env.On("FileContent", "/logs/refs/stash").Return(tc.StashContent)
g := &Git{ g := &Git{
scm: scm{ scm: scm{
@ -677,7 +677,7 @@ func TestGitUpstream(t *testing.T) {
{Case: "My custom server", Expected: "CU", Upstream: "mycustom.server/test"}, {Case: "My custom server", Expected: "CU", Upstream: "mycustom.server/test"},
} }
for _, tc := range cases { for _, tc := range cases {
env := &mock.MockedEnvironment{} env := &mock.Environment{}
env.On("IsWsl").Return(false) env.On("IsWsl").Return(false)
env.On("RunCommand", "git", []string{"-C", "", "--no-optional-locks", "-c", "core.quotepath=false", env.On("RunCommand", "git", []string{"-C", "", "--no-optional-locks", "-c", "core.quotepath=false",
"-c", "color.status=false", "remote", "get-url", "origin"}).Return(tc.Upstream, nil) "-c", "color.status=false", "remote", "get-url", "origin"}).Return(tc.Upstream, nil)
@ -875,7 +875,7 @@ func TestGitTemplateString(t *testing.T) {
props := properties.Map{ props := properties.Map{
FetchStatus: true, FetchStatus: true,
} }
env := new(mock.MockedEnvironment) env := new(mock.Environment)
tc.Git.env = env tc.Git.env = env
tc.Git.props = props tc.Git.props = props
assert.Equal(t, tc.Expected, renderTemplate(env, tc.Template, tc.Git), tc.Case) assert.Equal(t, tc.Expected, renderTemplate(env, tc.Template, tc.Git), tc.Case)
@ -1043,7 +1043,7 @@ func TestGitCommit(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.MockGitCommand("", tc.Output, "log", "-1", "--pretty=format:an:%an%nae:%ae%ncn:%cn%nce:%ce%nat:%at%nsu:%s%nha:%H") env.MockGitCommand("", tc.Output, "log", "-1", "--pretty=format:an:%an%nae:%ae%ncn:%cn%nce:%ce%nat:%at%nsu:%s%nha:%H")
g := &Git{ g := &Git{
scm: scm{ scm: scm{
@ -1095,7 +1095,7 @@ func TestGitRemotes(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("FileContent", "config").Return(tc.Config) env.On("FileContent", "config").Return(tc.Config)
g := &Git{ g := &Git{
@ -1140,7 +1140,7 @@ func TestGitRepoName(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("PathSeparator").Return("/") env.On("PathSeparator").Return("/")
env.On("GOOS").Return(runtime.LINUX) env.On("GOOS").Return(runtime.LINUX)

View file

@ -4,11 +4,12 @@ import (
"errors" "errors"
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock" cache_ "github.com/jandedobbeleer/oh-my-posh/src/cache/mock"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/alecthomas/assert" "github.com/alecthomas/assert"
mock2 "github.com/stretchr/testify/mock" testify_ "github.com/stretchr/testify/mock"
) )
func TestGitversion(t *testing.T) { func TestGitversion(t *testing.T) {
@ -70,14 +71,14 @@ func TestGitversion(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
cache := &mock.MockedCache{} cache := &cache_.Cache{}
env.On("HasCommand", "gitversion").Return(tc.HasGitversion) env.On("HasCommand", "gitversion").Return(tc.HasGitversion)
env.On("Pwd").Return("test-dir") env.On("Pwd").Return("test-dir")
env.On("Cache").Return(cache) env.On("Cache").Return(cache)
cache.On("Get", "test-dir").Return(tc.CacheResponse, len(tc.CacheResponse) != 0) cache.On("Get", "test-dir").Return(tc.CacheResponse, len(tc.CacheResponse) != 0)
cache.On("Set", mock2.Anything, mock2.Anything, mock2.Anything) cache.On("Set", testify_.Anything, testify_.Anything, testify_.Anything)
env.On("RunCommand", "gitversion", []string{"-output", "json"}).Return(tc.Response, tc.CommandError) env.On("RunCommand", "gitversion", []string{"-output", "json"}).Return(tc.Response, tc.CommandError)

View file

@ -7,9 +7,9 @@ import (
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
testify_mock "github.com/stretchr/testify/mock" testify_mock "github.com/stretchr/testify/mock"
"github.com/jandedobbeleer/oh-my-posh/src/mock"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime" "github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
) )
func TestHelmSegment(t *testing.T) { func TestHelmSegment(t *testing.T) {
@ -82,7 +82,7 @@ func TestHelmSegment(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("HasCommand", "helm").Return(tc.HelmExists) env.On("HasCommand", "helm").Return(tc.HelmExists)
env.On("RunCommand", "helm", []string{"version", "--short", "--template={{.Version}}"}).Return("v3.12.3", nil) env.On("RunCommand", "helm", []string{"version", "--short", "--template={{.Version}}"}).Return("v3.12.3", nil)

View file

@ -3,9 +3,9 @@ package segments
import ( import (
"net" "net"
"github.com/jandedobbeleer/oh-my-posh/src/http"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime" "github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/http"
) )
type ipData struct { type ipData struct {
@ -63,8 +63,11 @@ func (i *IPify) getResult() (string, error) {
} }
func (i *IPify) Init(props properties.Properties, env runtime.Environment) { func (i *IPify) Init(props properties.Properties, env runtime.Environment) {
request := &http.Request{} request := &http.Request{
request.Init(env, props) Env: env,
CacheTimeout: props.GetInt(properties.CacheTimeout, 30),
HTTPTimeout: props.GetInt(properties.HTTPTimeout, properties.DefaultHTTPTimeout),
}
i.api = &ipAPI{ i.api = &ipAPI{
Request: *request, Request: *request,

View file

@ -5,10 +5,10 @@ import (
"net" "net"
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock" "github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
mock2 "github.com/stretchr/testify/mock" testify_ "github.com/stretchr/testify/mock"
) )
const ( const (
@ -16,7 +16,7 @@ const (
) )
type mockedipAPI struct { type mockedipAPI struct {
mock2.Mock testify_.Mock
} }
func (s *mockedipAPI) Get() (*ipData, error) { func (s *mockedipAPI) Get() (*ipData, error) {
@ -66,6 +66,6 @@ func TestIpifySegment(t *testing.T) {
continue continue
} }
assert.Equal(t, tc.ExpectedString, renderTemplate(&mock.MockedEnvironment{}, ipify.Template(), ipify), tc.Case) assert.Equal(t, tc.ExpectedString, renderTemplate(&mock.Environment{}, ipify.Template(), ipify), tc.Case)
} }
} }

View file

@ -6,9 +6,9 @@ import (
"path/filepath" "path/filepath"
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime" "github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -132,7 +132,7 @@ func TestKubectlSegment(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("HasCommand", "kubectl").Return(tc.KubectlExists) env.On("HasCommand", "kubectl").Return(tc.KubectlExists)
var kubeconfig string var kubeconfig string
content, err := os.ReadFile("../test/kubectl.yml") content, err := os.ReadFile("../test/kubectl.yml")

View file

@ -3,12 +3,14 @@ package segments
import ( import (
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock" "github.com/jandedobbeleer/oh-my-posh/src/cache"
cache_ "github.com/jandedobbeleer/oh-my-posh/src/cache/mock"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime" "github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
mock2 "github.com/stretchr/testify/mock" testify_ "github.com/stretchr/testify/mock"
) )
const ( const (
@ -41,7 +43,7 @@ func (l *languageArgs) hasvalue(value string, list []string) bool {
} }
func bootStrapLanguageTest(args *languageArgs) *language { func bootStrapLanguageTest(args *languageArgs) *language {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
for _, command := range args.commands { for _, command := range args.commands {
env.On("HasCommand", command.executable).Return(args.hasvalue(command.executable, args.enabledCommands)) env.On("HasCommand", command.executable).Return(args.hasvalue(command.executable, args.enabledCommands))
@ -60,15 +62,15 @@ func bootStrapLanguageTest(args *languageArgs) *language {
env.On("Pwd").Return(cwd) env.On("Pwd").Return(cwd)
env.On("Home").Return(home) env.On("Home").Return(home)
env.On("DebugF", mock2.Anything, mock2.Anything).Return(nil) env.On("DebugF", testify_.Anything, testify_.Anything).Return(nil)
env.On("TemplateCache").Return(&runtime.TemplateCache{ env.On("TemplateCache").Return(&cache.Template{
Env: make(map[string]string), Env: make(map[string]string),
}) })
cache := &mock.MockedCache{} c := &cache_.Cache{}
cache.On("Get", mock2.Anything).Return(args.cachedVersion, len(args.cachedVersion) > 0) c.On("Get", testify_.Anything).Return(args.cachedVersion, len(args.cachedVersion) > 0)
cache.On("Set", mock2.Anything, mock2.Anything, mock2.Anything) c.On("Set", testify_.Anything, testify_.Anything, testify_.Anything)
env.On("Cache").Return(cache) env.On("Cache").Return(c)
if args.properties == nil { if args.properties == nil {
args.properties = properties.Map{} args.properties = properties.Map{}
@ -570,25 +572,25 @@ type mockedLanguageParams struct {
extension string extension string
} }
func getMockedLanguageEnv(params *mockedLanguageParams) (*mock.MockedEnvironment, properties.Map) { func getMockedLanguageEnv(params *mockedLanguageParams) (*mock.Environment, properties.Map) {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("HasCommand", params.cmd).Return(true) env.On("HasCommand", params.cmd).Return(true)
env.On("RunCommand", params.cmd, []string{params.versionParam}).Return(params.versionOutput, nil) env.On("RunCommand", params.cmd, []string{params.versionParam}).Return(params.versionOutput, nil)
env.On("HasFiles", params.extension).Return(true) env.On("HasFiles", params.extension).Return(true)
env.On("Pwd").Return("/usr/home/project") env.On("Pwd").Return("/usr/home/project")
env.On("Home").Return("/usr/home") env.On("Home").Return("/usr/home")
env.On("TemplateCache").Return(&runtime.TemplateCache{ env.On("TemplateCache").Return(&cache.Template{
Env: make(map[string]string), Env: make(map[string]string),
}) })
env.On("DebugF", mock2.Anything, mock2.Anything).Return(nil) env.On("DebugF", testify_.Anything, testify_.Anything).Return(nil)
props := properties.Map{ props := properties.Map{
properties.FetchVersion: true, properties.FetchVersion: true,
} }
cache := &mock.MockedCache{} c := &cache_.Cache{}
cache.On("Get", mock2.Anything).Return("", false) c.On("Get", testify_.Anything).Return("", false)
cache.On("Set", mock2.Anything, mock2.Anything, mock2.Anything) c.On("Set", testify_.Anything, testify_.Anything, testify_.Anything)
env.On("Cache").Return(cache) env.On("Cache").Return(c)
return env, props return env, props
} }

View file

@ -4,11 +4,12 @@ import (
"errors" "errors"
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock" cache_ "github.com/jandedobbeleer/oh-my-posh/src/cache/mock"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
mock2 "github.com/stretchr/testify/mock" testify_ "github.com/stretchr/testify/mock"
) )
const ( const (
@ -53,7 +54,7 @@ func TestLFMSegmentSingle(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := &mock.MockedEnvironment{} env := &mock.Environment{}
var props properties.Map = properties.Map{ var props properties.Map = properties.Map{
APIKey: "key", APIKey: "key",
Username: "KibbeWater", Username: "KibbeWater",
@ -62,7 +63,7 @@ func TestLFMSegmentSingle(t *testing.T) {
} }
env.On("HTTPRequest", LFMAPIURL).Return([]byte(tc.APIJSONResponse), tc.Error) env.On("HTTPRequest", LFMAPIURL).Return([]byte(tc.APIJSONResponse), tc.Error)
env.On("Error", mock2.Anything) env.On("Error", testify_.Anything)
o := &LastFM{ o := &LastFM{
props: props, props: props,
@ -86,8 +87,8 @@ func TestLFMSegmentFromCache(t *testing.T) {
response := `{"recenttracks":{"track":[{"artist":{"mbid":"","#text":"C.Gambino"},"streamable":"0","name":"Automatic","date":{"uts":"1699350223","#text":"07 Nov 2023, 09:43"}}]}}` response := `{"recenttracks":{"track":[{"artist":{"mbid":"","#text":"C.Gambino"},"streamable":"0","name":"Automatic","date":{"uts":"1699350223","#text":"07 Nov 2023, 09:43"}}]}}`
expectedString := "\uF04D" expectedString := "\uF04D"
env := &mock.MockedEnvironment{} env := &mock.Environment{}
cache := &mock.MockedCache{} cache := &cache_.Cache{}
o := &LastFM{ o := &LastFM{
props: properties.Map{ props: properties.Map{
APIKey: "key", APIKey: "key",

View file

@ -3,14 +3,14 @@ package segments
import ( import (
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime" "github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
func TestMercurialEnabledToolNotFound(t *testing.T) { func TestMercurialEnabledToolNotFound(t *testing.T) {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("InWSLSharedDrive").Return(false) env.On("InWSLSharedDrive").Return(false)
env.On("HasCommand", "hg").Return(false) env.On("HasCommand", "hg").Return(false)
env.On("GOOS").Return("") env.On("GOOS").Return("")
@ -32,7 +32,7 @@ func TestMercurialEnabledInWorkingDirectory(t *testing.T) {
ParentFolder: "/dir", ParentFolder: "/dir",
IsDir: true, IsDir: true,
} }
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("InWSLSharedDrive").Return(false) env.On("InWSLSharedDrive").Return(false)
env.On("HasCommand", "hg").Return(true) env.On("HasCommand", "hg").Return(true)
env.On("GOOS").Return("") env.On("GOOS").Return("")
@ -146,7 +146,7 @@ A Added.File
FetchStatus: true, FetchStatus: true,
} }
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("InWSLSharedDrive").Return(false) env.On("InWSLSharedDrive").Return(false)
env.On("HasCommand", "hg").Return(true) env.On("HasCommand", "hg").Return(true)
env.On("GOOS").Return("") env.On("GOOS").Return("")

View file

@ -6,11 +6,12 @@ import (
"testing" "testing"
"time" "time"
"github.com/jandedobbeleer/oh-my-posh/src/mock" cache_ "github.com/jandedobbeleer/oh-my-posh/src/cache/mock"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
mock2 "github.com/stretchr/testify/mock" testify_ "github.com/stretchr/testify/mock"
) )
func getTestData(file string) string { func getTestData(file string) string {
@ -74,15 +75,15 @@ func TestNBASegment(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := &mock.MockedEnvironment{} env := &mock.Environment{}
props := properties.Map{ props := properties.Map{
properties.CacheTimeout: tc.CacheTimeout, properties.CacheTimeout: tc.CacheTimeout,
TeamName: tc.TeamName, TeamName: tc.TeamName,
DaysOffset: tc.DaysOffset, DaysOffset: tc.DaysOffset,
} }
env.On("Error", mock2.Anything) env.On("Error", testify_.Anything)
env.On("Debug", mock2.Anything) env.On("Debug", testify_.Anything)
env.On("HTTPRequest", NBAScoreURL).Return([]byte(tc.JSONResponse), tc.Error) env.On("HTTPRequest", NBAScoreURL).Return([]byte(tc.JSONResponse), tc.Error)
// Add all the daysOffset to the http request responses // Add all the daysOffset to the http request responses
@ -103,7 +104,7 @@ func TestNBASegment(t *testing.T) {
cachedScheduleKey := fmt.Sprintf("%s%s", tc.TeamName, "schedule") cachedScheduleKey := fmt.Sprintf("%s%s", tc.TeamName, "schedule")
cachedScoreKey := fmt.Sprintf("%s%s", tc.TeamName, "score") cachedScoreKey := fmt.Sprintf("%s%s", tc.TeamName, "score")
cache := &mock.MockedCache{} cache := &cache_.Cache{}
cache.On("Get", cachedScheduleKey).Return(nba.getGameNotFoundData(), tc.CacheFoundFail) cache.On("Get", cachedScheduleKey).Return(nba.getGameNotFoundData(), tc.CacheFoundFail)
cache.On("Get", cachedScoreKey).Return(nba.getGameNotFoundData(), tc.CacheFoundFail) cache.On("Get", cachedScoreKey).Return(nba.getGameNotFoundData(), tc.CacheFoundFail)
cache.On("Set", cachedScheduleKey, nba.getGameNotFoundData(), tc.CacheTimeout).Return() cache.On("Set", cachedScheduleKey, nba.getGameNotFoundData(), tc.CacheTimeout).Return()

View file

@ -4,8 +4,8 @@ import (
"errors" "errors"
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/alecthomas/assert" "github.com/alecthomas/assert"
) )
@ -60,7 +60,7 @@ func TestNbgv(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("HasCommand", "nbgv").Return(tc.HasNbgv) env.On("HasCommand", "nbgv").Return(tc.HasNbgv)
env.On("RunCommand", "nbgv", []string{"get-version", "--format=json"}).Return(tc.Response, tc.Error) env.On("RunCommand", "nbgv", []string{"get-version", "--format=json"}).Return(tc.Response, tc.Error)
nbgv := &Nbgv{ nbgv := &Nbgv{

View file

@ -4,8 +4,9 @@ import (
"errors" "errors"
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock" cache_ "github.com/jandedobbeleer/oh-my-posh/src/cache/mock"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -132,14 +133,14 @@ func TestNSSegment(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := &mock.MockedEnvironment{} env := &mock.Environment{}
props := properties.Map{ props := properties.Map{
properties.CacheTimeout: tc.CacheTimeout, properties.CacheTimeout: tc.CacheTimeout,
URL: "FAKE", URL: "FAKE",
Headers: map[string]string{"Fake-Header": "xxxxx"}, Headers: map[string]string{"Fake-Header": "xxxxx"},
} }
cache := &mock.MockedCache{} cache := &cache_.Cache{}
cache.On("Get", FAKEAPIURL).Return(tc.JSONResponse, !tc.CacheFoundFail) cache.On("Get", FAKEAPIURL).Return(tc.JSONResponse, !tc.CacheFoundFail)
cache.On("Set", FAKEAPIURL, tc.JSONResponse, tc.CacheTimeout).Return() cache.On("Set", FAKEAPIURL, tc.JSONResponse, tc.CacheTimeout).Return()

View file

@ -3,8 +3,8 @@ package segments
import ( import (
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/alecthomas/assert" "github.com/alecthomas/assert"
) )
@ -37,7 +37,7 @@ func TestNodeMatchesVersionFile(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("FileContent", ".nvmrc").Return(tc.RCVersion) env.On("FileContent", ".nvmrc").Return(tc.RCVersion)
node := &Node{ node := &Node{
@ -75,7 +75,7 @@ func TestNodeInContext(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("HasFiles", "pnpm-lock.yaml").Return(tc.hasPNPM) env.On("HasFiles", "pnpm-lock.yaml").Return(tc.hasPNPM)
env.On("HasFiles", "yarn.lock").Return(tc.hasYarn) env.On("HasFiles", "yarn.lock").Return(tc.hasYarn)
env.On("HasFiles", "package-lock.json").Return(tc.hasNPM) env.On("HasFiles", "package-lock.json").Return(tc.hasNPM)

View file

@ -4,8 +4,8 @@ import (
"path/filepath" "path/filepath"
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock" "github.com/jandedobbeleer/oh-my-posh/src/cache"
"github.com/jandedobbeleer/oh-my-posh/src/runtime" "github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -25,13 +25,13 @@ func TestGetNodePackageVersion(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
var env = new(mock.MockedEnvironment) var env = new(mock.Environment)
// mock getVersion methods // mock getVersion methods
env.On("Pwd").Return("posh") env.On("Pwd").Return("posh")
path := filepath.Join("posh", "node_modules", "nx") path := filepath.Join("posh", "node_modules", "nx")
env.On("HasFilesInDir", path, "package.json").Return(!tc.NoFiles) env.On("HasFilesInDir", path, "package.json").Return(!tc.NoFiles)
env.On("FileContent", filepath.Join(path, "package.json")).Return(tc.PackageJSON) env.On("FileContent", filepath.Join(path, "package.json")).Return(tc.PackageJSON)
env.On("TemplateCache").Return(&runtime.TemplateCache{ env.On("TemplateCache").Return(&cache.Template{
Env: make(map[string]string), Env: make(map[string]string),
}) })
got, err := getNodePackageVersion(env, "nx") got, err := getNodePackageVersion(env, "nx")

View file

@ -3,9 +3,9 @@ package segments
import ( import (
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock" "github.com/jandedobbeleer/oh-my-posh/src/cache"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime" "github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -86,10 +86,10 @@ func TestOSInfo(t *testing.T) {
}, },
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("GOOS").Return(tc.GOOS) env.On("GOOS").Return(tc.GOOS)
env.On("Platform").Return(tc.Platform) env.On("Platform").Return(tc.Platform)
env.On("TemplateCache").Return(&runtime.TemplateCache{ env.On("TemplateCache").Return(&cache.Template{
Env: make(map[string]string), Env: make(map[string]string),
WSL: tc.IsWSL, WSL: tc.IsWSL,
}) })

View file

@ -6,11 +6,12 @@ import (
"net/url" "net/url"
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock" cache_ "github.com/jandedobbeleer/oh-my-posh/src/cache/mock"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
mock2 "github.com/stretchr/testify/mock" testify_ "github.com/stretchr/testify/mock"
) )
const ( const (
@ -72,7 +73,7 @@ func TestOWMSegmentSingle(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := &mock.MockedEnvironment{} env := &mock.Environment{}
props := properties.Map{ props := properties.Map{
APIKey: "key", APIKey: "key",
Location: tc.Location, Location: tc.Location,
@ -83,7 +84,7 @@ func TestOWMSegmentSingle(t *testing.T) {
location := url.QueryEscape(tc.Location) location := url.QueryEscape(tc.Location)
testURL := fmt.Sprintf(OWMWEATHERAPIURL, location) testURL := fmt.Sprintf(OWMWEATHERAPIURL, location)
env.On("HTTPRequest", testURL).Return([]byte(tc.WeatherJSONResponse), tc.Error) env.On("HTTPRequest", testURL).Return([]byte(tc.WeatherJSONResponse), tc.Error)
env.On("Error", mock2.Anything) env.On("Error", testify_.Anything)
o := &Owm{ o := &Owm{
props: props, props: props,
@ -206,7 +207,7 @@ func TestOWMSegmentIcons(t *testing.T) {
testURL := fmt.Sprintf(OWMWEATHERAPIURL, location) testURL := fmt.Sprintf(OWMWEATHERAPIURL, location)
for _, tc := range cases { for _, tc := range cases {
env := &mock.MockedEnvironment{} env := &mock.Environment{}
weatherResponse := fmt.Sprintf(`{"weather":[{"icon":"%s"}],"main":{"temp":20.3}}`, tc.IconID) weatherResponse := fmt.Sprintf(`{"weather":[{"icon":"%s"}],"main":{"temp":20.3}}`, tc.IconID)
expectedString := fmt.Sprintf("%s (20°C)", tc.ExpectedIconString) expectedString := fmt.Sprintf("%s (20°C)", tc.ExpectedIconString)
@ -229,7 +230,7 @@ func TestOWMSegmentIcons(t *testing.T) {
// test with hyperlink enabled // test with hyperlink enabled
for _, tc := range cases { for _, tc := range cases {
env := &mock.MockedEnvironment{} env := &mock.Environment{}
weatherResponse := fmt.Sprintf(`{"weather":[{"icon":"%s"}],"main":{"temp":20.3}}`, tc.IconID) weatherResponse := fmt.Sprintf(`{"weather":[{"icon":"%s"}],"main":{"temp":20.3}}`, tc.IconID)
expectedString := fmt.Sprintf("«%s (20°C)»(%s)", tc.ExpectedIconString, testURL) expectedString := fmt.Sprintf("«%s (20°C)»(%s)", tc.ExpectedIconString, testURL)
@ -255,8 +256,8 @@ func TestOWMSegmentFromCacheByGeoName(t *testing.T) {
response := fmt.Sprintf(`{"weather":[{"icon":"%s"}],"main":{"temp":20}}`, "01d") response := fmt.Sprintf(`{"weather":[{"icon":"%s"}],"main":{"temp":20}}`, "01d")
expectedString := fmt.Sprintf("%s (20°C)", "\ue30d") expectedString := fmt.Sprintf("%s (20°C)", "\ue30d")
env := &mock.MockedEnvironment{} env := &mock.Environment{}
cache := &mock.MockedCache{} cache := &cache_.Cache{}
o := &Owm{ o := &Owm{
props: properties.Map{ props: properties.Map{
APIKey: "key", APIKey: "key",
@ -278,8 +279,8 @@ func TestOWMSegmentFromCacheWithHyperlinkByGeoName(t *testing.T) {
response := fmt.Sprintf(`{"weather":[{"icon":"%s"}],"main":{"temp":20}}`, "01d") response := fmt.Sprintf(`{"weather":[{"icon":"%s"}],"main":{"temp":20}}`, "01d")
expectedString := fmt.Sprintf("«%s (20°C)»(http://api.openweathermap.org/data/2.5/weather?q=AMSTERDAM,NL&units=metric&appid=key)", "\ue30d") expectedString := fmt.Sprintf("«%s (20°C)»(http://api.openweathermap.org/data/2.5/weather?q=AMSTERDAM,NL&units=metric&appid=key)", "\ue30d")
env := &mock.MockedEnvironment{} env := &mock.Environment{}
cache := &mock.MockedCache{} cache := &cache_.Cache{}
o := &Owm{ o := &Owm{
props: properties.Map{ props: properties.Map{

View file

@ -5,14 +5,15 @@ import (
"strings" "strings"
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock" "github.com/jandedobbeleer/oh-my-posh/src/cache"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime" "github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/jandedobbeleer/oh-my-posh/src/shell" "github.com/jandedobbeleer/oh-my-posh/src/shell"
"github.com/jandedobbeleer/oh-my-posh/src/template" "github.com/jandedobbeleer/oh-my-posh/src/template"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
mock2 "github.com/stretchr/testify/mock" testify_ "github.com/stretchr/testify/mock"
) )
const ( const (
@ -24,7 +25,7 @@ const (
cdefg = "/c/d/e/f/g" cdefg = "/c/d/e/f/g"
) )
func renderTemplateNoTrimSpace(env *mock.MockedEnvironment, segmentTemplate string, context any) string { func renderTemplateNoTrimSpace(env *mock.Environment, segmentTemplate string, context any) string {
found := false found := false
for _, call := range env.Mock.ExpectedCalls { for _, call := range env.Mock.ExpectedCalls {
if call.Method == "TemplateCache" { if call.Method == "TemplateCache" {
@ -33,13 +34,13 @@ func renderTemplateNoTrimSpace(env *mock.MockedEnvironment, segmentTemplate stri
} }
} }
if !found { if !found {
env.On("TemplateCache").Return(&runtime.TemplateCache{ env.On("TemplateCache").Return(&cache.Template{
Env: make(map[string]string), Env: make(map[string]string),
}) })
} }
env.On("Error", mock2.Anything) env.On("Error", testify_.Anything)
env.On("Debug", mock2.Anything) env.On("Debug", testify_.Anything)
env.On("DebugF", mock2.Anything, mock2.Anything).Return(nil) env.On("DebugF", testify_.Anything, testify_.Anything).Return(nil)
tmpl := &template.Text{ tmpl := &template.Text{
Template: segmentTemplate, Template: segmentTemplate,
Context: context, Context: context,
@ -52,7 +53,7 @@ func renderTemplateNoTrimSpace(env *mock.MockedEnvironment, segmentTemplate stri
return text return text
} }
func renderTemplate(env *mock.MockedEnvironment, segmentTemplate string, context any) string { func renderTemplate(env *mock.Environment, segmentTemplate string, context any) string {
return strings.TrimSpace(renderTemplateNoTrimSpace(env, segmentTemplate, context)) return strings.TrimSpace(renderTemplateNoTrimSpace(env, segmentTemplate, context))
} }
@ -141,7 +142,7 @@ func TestParent(t *testing.T) {
}, },
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("Home").Return(tc.HomePath) env.On("Home").Return(tc.HomePath)
env.On("Pwd").Return(tc.Pwd) env.On("Pwd").Return(tc.Pwd)
env.On("Flags").Return(&runtime.Flags{}) env.On("Flags").Return(&runtime.Flags{})
@ -758,7 +759,7 @@ func TestAgnosterPathStyles(t *testing.T) {
}, },
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("PathSeparator").Return(tc.PathSeparator) env.On("PathSeparator").Return(tc.PathSeparator)
env.On("Home").Return(tc.HomePath) env.On("Home").Return(tc.HomePath)
env.On("Pwd").Return(tc.Pwd) env.On("Pwd").Return(tc.Pwd)
@ -775,12 +776,12 @@ func TestAgnosterPathStyles(t *testing.T) {
} }
env.On("Shell").Return(tc.Shell) env.On("Shell").Return(tc.Shell)
env.On("DebugF", mock2.Anything, mock2.Anything).Return(nil) env.On("DebugF", testify_.Anything, testify_.Anything).Return(nil)
displayCygpath := tc.GOOS == runtime.WINDOWS && tc.Shell == shell.BASH displayCygpath := tc.GOOS == runtime.WINDOWS && tc.Shell == shell.BASH
if displayCygpath { if displayCygpath {
env.On("RunCommand", "cygpath", []string{"-u", tc.Pwd}).Return(tc.Cygpath, tc.CygpathError) env.On("RunCommand", "cygpath", []string{"-u", tc.Pwd}).Return(tc.Cygpath, tc.CygpathError)
env.On("RunCommand", "cygpath", mock2.Anything).Return("brrrr", nil) env.On("RunCommand", "cygpath", testify_.Anything).Return("brrrr", nil)
} }
path := &Path{ path := &Path{
@ -889,7 +890,7 @@ func TestFullAndFolderPath(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
if len(tc.PathSeparator) == 0 { if len(tc.PathSeparator) == 0 {
tc.PathSeparator = "/" tc.PathSeparator = "/"
} }
@ -951,7 +952,7 @@ func TestFullPathCustomMappedLocations(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("Home").Return(homeDir) env.On("Home").Return(homeDir)
env.On("Pwd").Return(tc.Pwd) env.On("Pwd").Return(tc.Pwd)
@ -972,8 +973,8 @@ func TestFullPathCustomMappedLocations(t *testing.T) {
env.On("Flags").Return(args) env.On("Flags").Return(args)
env.On("Shell").Return(shell.GENERIC) env.On("Shell").Return(shell.GENERIC)
env.On("DebugF", mock2.Anything, mock2.Anything).Return(nil) env.On("DebugF", testify_.Anything, testify_.Anything).Return(nil)
env.On("TemplateCache").Return(&runtime.TemplateCache{ env.On("TemplateCache").Return(&cache.Template{
Env: map[string]string{ Env: map[string]string{
"HOME": "/a/b/c", "HOME": "/a/b/c",
}, },
@ -1005,13 +1006,13 @@ func TestPowerlevelMappedLocations(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("Home").Return("/Users/michal") env.On("Home").Return("/Users/michal")
env.On("Pwd").Return(tc.Pwd) env.On("Pwd").Return(tc.Pwd)
env.On("GOOS").Return(runtime.DARWIN) env.On("GOOS").Return(runtime.DARWIN)
env.On("PathSeparator").Return("/") env.On("PathSeparator").Return("/")
env.On("Shell").Return(shell.GENERIC) env.On("Shell").Return(shell.GENERIC)
env.On("DebugF", mock2.Anything, mock2.Anything).Return(nil) env.On("DebugF", testify_.Anything, testify_.Anything).Return(nil)
path := &Path{ path := &Path{
env: env, env: env,
props: properties.Map{ props: properties.Map{
@ -1028,7 +1029,7 @@ func TestPowerlevelMappedLocations(t *testing.T) {
func TestFolderPathCustomMappedLocations(t *testing.T) { func TestFolderPathCustomMappedLocations(t *testing.T) {
pwd := abcd pwd := abcd
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("PathSeparator").Return("/") env.On("PathSeparator").Return("/")
env.On("Home").Return(homeDir) env.On("Home").Return(homeDir)
env.On("Pwd").Return(pwd) env.On("Pwd").Return(pwd)
@ -1038,7 +1039,7 @@ func TestFolderPathCustomMappedLocations(t *testing.T) {
} }
env.On("Flags").Return(args) env.On("Flags").Return(args)
env.On("Shell").Return(shell.GENERIC) env.On("Shell").Return(shell.GENERIC)
env.On("DebugF", mock2.Anything, mock2.Anything).Return(nil) env.On("DebugF", testify_.Anything, testify_.Anything).Return(nil)
path := &Path{ path := &Path{
env: env, env: env,
props: properties.Map{ props: properties.Map{
@ -1208,7 +1209,7 @@ func TestAgnosterPath(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("Home").Return(tc.Home) env.On("Home").Return(tc.Home)
env.On("PathSeparator").Return(tc.PathSeparator) env.On("PathSeparator").Return(tc.PathSeparator)
env.On("Pwd").Return(tc.PWD) env.On("Pwd").Return(tc.PWD)
@ -1364,7 +1365,7 @@ func TestAgnosterLeftPath(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("Home").Return(tc.Home) env.On("Home").Return(tc.Home)
env.On("PathSeparator").Return(tc.PathSeparator) env.On("PathSeparator").Return(tc.PathSeparator)
env.On("Pwd").Return(tc.PWD) env.On("Pwd").Return(tc.PWD)
@ -1417,7 +1418,7 @@ func TestGetPwd(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("PathSeparator").Return("/") env.On("PathSeparator").Return("/")
env.On("Home").Return(homeDir) env.On("Home").Return(homeDir)
env.On("Pwd").Return(tc.Pwd) env.On("Pwd").Return(tc.Pwd)
@ -1427,7 +1428,7 @@ func TestGetPwd(t *testing.T) {
} }
env.On("Flags").Return(args) env.On("Flags").Return(args)
env.On("Shell").Return(shell.PWSH) env.On("Shell").Return(shell.PWSH)
env.On("DebugF", mock2.Anything, mock2.Anything).Return(nil) env.On("DebugF", testify_.Anything, testify_.Anything).Return(nil)
path := &Path{ path := &Path{
env: env, env: env,
props: properties.Map{ props: properties.Map{
@ -1457,10 +1458,10 @@ func TestGetFolderSeparator(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("Error", mock2.Anything) env.On("Error", testify_.Anything)
env.On("Debug", mock2.Anything) env.On("Debug", testify_.Anything)
env.On("DebugF", mock2.Anything, mock2.Anything).Return(nil) env.On("DebugF", testify_.Anything, testify_.Anything).Return(nil)
path := &Path{ path := &Path{
env: env, env: env,
pathSeparator: "/", pathSeparator: "/",
@ -1476,7 +1477,7 @@ func TestGetFolderSeparator(t *testing.T) {
props[FolderSeparatorIcon] = tc.FolderSeparatorIcon props[FolderSeparatorIcon] = tc.FolderSeparatorIcon
} }
env.On("TemplateCache").Return(&runtime.TemplateCache{ env.On("TemplateCache").Return(&cache.Template{
Env: make(map[string]string), Env: make(map[string]string),
Shell: "bash", Shell: "bash",
}) })
@ -1505,7 +1506,7 @@ func TestNormalizePath(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("Home").Return(tc.HomeDir) env.On("Home").Return(tc.HomeDir)
env.On("GOOS").Return(tc.GOOS) env.On("GOOS").Return(tc.GOOS)
pt := &Path{ pt := &Path{
@ -1532,13 +1533,13 @@ func TestReplaceMappedLocations(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("PathSeparator").Return("/") env.On("PathSeparator").Return("/")
env.On("Pwd").Return(tc.Pwd) env.On("Pwd").Return(tc.Pwd)
env.On("Shell").Return(shell.FISH) env.On("Shell").Return(shell.FISH)
env.On("GOOS").Return(runtime.DARWIN) env.On("GOOS").Return(runtime.DARWIN)
env.On("Home").Return("/a/b/k") env.On("Home").Return("/a/b/k")
env.On("DebugF", mock2.Anything, mock2.Anything).Return(nil) env.On("DebugF", testify_.Anything, testify_.Anything).Return(nil)
path := &Path{ path := &Path{
env: env, env: env,
props: properties.Map{ props: properties.Map{
@ -1606,7 +1607,7 @@ func TestSplitPath(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("Home").Return("/a/b") env.On("Home").Return("/a/b")
env.On("HasParentFilePath", ".git").Return(tc.GitDir, nil) env.On("HasParentFilePath", ".git").Return(tc.GitDir, nil)
env.On("GOOS").Return(tc.GOOS) env.On("GOOS").Return(tc.GOOS)
@ -1655,10 +1656,10 @@ func TestGetMaxWidth(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("DebugF", mock2.Anything, mock2.Anything).Return(nil) env.On("DebugF", testify_.Anything, testify_.Anything).Return(nil)
env.On("Error", mock2.Anything).Return(nil) env.On("Error", testify_.Anything).Return(nil)
env.On("TemplateCache").Return(&runtime.TemplateCache{ env.On("TemplateCache").Return(&cache.Template{
Env: map[string]string{ Env: map[string]string{
"MAX_WIDTH": "120", "MAX_WIDTH": "120",
}, },

View file

@ -3,15 +3,15 @@ package segments
import ( import (
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime" "github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
func TestPlasticEnabledNotFound(t *testing.T) { func TestPlasticEnabledNotFound(t *testing.T) {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("HasCommand", "cm").Return(false) env.On("HasCommand", "cm").Return(false)
env.On("GOOS").Return("") env.On("GOOS").Return("")
env.On("IsWsl").Return(false) env.On("IsWsl").Return(false)
@ -25,7 +25,7 @@ func TestPlasticEnabledNotFound(t *testing.T) {
} }
func TestPlasticEnabledInWorkspaceDirectory(t *testing.T) { func TestPlasticEnabledInWorkspaceDirectory(t *testing.T) {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("HasCommand", "cm").Return(true) env.On("HasCommand", "cm").Return(true)
env.On("GOOS").Return("") env.On("GOOS").Return("")
env.On("IsWsl").Return(false) env.On("IsWsl").Return(false)
@ -47,7 +47,7 @@ func TestPlasticEnabledInWorkspaceDirectory(t *testing.T) {
} }
func setupCmStatusEnv(status, headStatus string) *Plastic { func setupCmStatusEnv(status, headStatus string) *Plastic {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("RunCommand", "cm", []string{"status", "--all", "--machinereadable"}).Return(status, nil) env.On("RunCommand", "cm", []string{"status", "--all", "--machinereadable"}).Return(status, nil)
env.On("RunCommand", "cm", []string{"status", "--head", "--machinereadable"}).Return(headStatus, nil) env.On("RunCommand", "cm", []string{"status", "--head", "--machinereadable"}).Return(headStatus, nil)
p := &Plastic{ p := &Plastic{
@ -333,7 +333,7 @@ func TestPlasticTemplateString(t *testing.T) {
FetchStatus: true, FetchStatus: true,
} }
tc.Plastic.props = props tc.Plastic.props = props
env := new(mock.MockedEnvironment) env := new(mock.Environment)
tc.Plastic.env = env tc.Plastic.env = env
assert.Equal(t, tc.Expected, renderTemplate(env, tc.Template, tc.Plastic), tc.Case) assert.Equal(t, tc.Expected, renderTemplate(env, tc.Template, tc.Plastic), tc.Case)
} }

View file

@ -3,9 +3,9 @@ package segments
import ( import (
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime" "github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -182,7 +182,7 @@ func TestPoshGitSegment(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("Getenv", poshGitEnv).Return(tc.PoshGitJSON) env.On("Getenv", poshGitEnv).Return(tc.PoshGitJSON)
env.On("Home").Return("/Users/bill") env.On("Home").Return("/Users/bill")
env.On("GOOS").Return(runtime.LINUX) env.On("GOOS").Return(runtime.LINUX)

View file

@ -6,13 +6,12 @@ import (
"path/filepath" "path/filepath"
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/alecthomas/assert" "github.com/alecthomas/assert"
mock2 "github.com/stretchr/testify/mock" testify_ "github.com/stretchr/testify/mock"
testify_mock "github.com/stretchr/testify/mock"
) )
const ( const (
@ -256,11 +255,11 @@ func TestPackage(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On(hasFiles, testify_mock.Anything).Run(func(args testify_mock.Arguments) { env.On(hasFiles, testify_.Anything).Run(func(args testify_.Arguments) {
for _, c := range env.ExpectedCalls { for _, c := range env.ExpectedCalls {
if c.Method == hasFiles { if c.Method == hasFiles {
c.ReturnArguments = testify_mock.Arguments{args.Get(0).(string) == tc.File} c.ReturnArguments = testify_.Arguments{args.Get(0).(string) == tc.File}
} }
} }
}) })
@ -309,17 +308,17 @@ func TestNuspecPackage(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On(hasFiles, testify_mock.Anything).Run(func(args testify_mock.Arguments) { env.On(hasFiles, testify_.Anything).Run(func(args testify_.Arguments) {
for _, c := range env.ExpectedCalls { for _, c := range env.ExpectedCalls {
if c.Method != hasFiles { if c.Method != hasFiles {
continue continue
} }
if args.Get(0).(string) == "*.nuspec" { if args.Get(0).(string) == "*.nuspec" {
c.ReturnArguments = testify_mock.Arguments{tc.HasFiles} c.ReturnArguments = testify_.Arguments{tc.HasFiles}
continue continue
} }
c.ReturnArguments = testify_mock.Arguments{false} c.ReturnArguments = testify_.Arguments{false}
} }
}) })
env.On("Pwd").Return("posh") env.On("Pwd").Return("posh")
@ -387,12 +386,12 @@ func TestDotnetProject(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On(hasFiles, testify_mock.Anything).Run(func(args testify_mock.Arguments) { env.On(hasFiles, testify_.Anything).Run(func(args testify_.Arguments) {
for _, c := range env.ExpectedCalls { for _, c := range env.ExpectedCalls {
if c.Method == hasFiles { if c.Method == hasFiles {
pattern := "*" + filepath.Ext(tc.FileName) pattern := "*" + filepath.Ext(tc.FileName)
c.ReturnArguments = testify_mock.Arguments{args.Get(0).(string) == pattern} c.ReturnArguments = testify_.Arguments{args.Get(0).(string) == pattern}
} }
} }
}) })
@ -403,7 +402,7 @@ func TestDotnetProject(t *testing.T) {
}, },
}) })
env.On("FileContent", tc.FileName).Return(tc.ProjectContents) env.On("FileContent", tc.FileName).Return(tc.ProjectContents)
env.On("Error", mock2.Anything) env.On("Error", testify_.Anything)
pkg := &Project{} pkg := &Project{}
pkg.Init(properties.Map{}, env) pkg.Init(properties.Map{}, env)
assert.Equal(t, tc.ExpectedEnabled, pkg.Enabled(), tc.Case) assert.Equal(t, tc.ExpectedEnabled, pkg.Enabled(), tc.Case)
@ -429,11 +428,11 @@ func TestPowerShellModuleProject(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On(hasFiles, testify_mock.Anything).Run(func(args testify_mock.Arguments) { env.On(hasFiles, testify_.Anything).Run(func(args testify_.Arguments) {
for _, c := range env.ExpectedCalls { for _, c := range env.ExpectedCalls {
if c.Method == hasFiles { if c.Method == hasFiles {
c.ReturnArguments = testify_mock.Arguments{args.Get(0).(string) == "*.psd1"} c.ReturnArguments = testify_.Arguments{args.Get(0).(string) == "*.psd1"}
} }
} }
}) })

View file

@ -5,10 +5,11 @@ import (
"path/filepath" "path/filepath"
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock" cache_ "github.com/jandedobbeleer/oh-my-posh/src/cache/mock"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
mock2 "github.com/stretchr/testify/mock" testify_ "github.com/stretchr/testify/mock"
) )
func TestPulumi(t *testing.T) { func TestPulumi(t *testing.T) {
@ -185,7 +186,7 @@ description: A Console App
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("HasCommand", "pulumi").Return(tc.HasCommand) env.On("HasCommand", "pulumi").Return(tc.HasCommand)
env.On("RunCommand", "pulumi", []string{"stack", "ls", "--json"}).Return(tc.Stack, tc.StackError) env.On("RunCommand", "pulumi", []string{"stack", "ls", "--json"}).Return(tc.Stack, tc.StackError)
@ -193,9 +194,9 @@ description: A Console App
env.On("Pwd").Return("/home/foobar/Work/oh-my-posh/pulumi/projects/awesome-project") env.On("Pwd").Return("/home/foobar/Work/oh-my-posh/pulumi/projects/awesome-project")
env.On("Home").Return(filepath.Clean("/home/foobar")) env.On("Home").Return(filepath.Clean("/home/foobar"))
env.On("Error", mock2.Anything) env.On("Error", testify_.Anything)
env.On("Debug", mock2.Anything) env.On("Debug", testify_.Anything)
env.On("DebugF", mock2.Anything, mock2.Anything) env.On("DebugF", testify_.Anything, testify_.Anything)
env.On("HasFiles", pulumiYAML).Return(len(tc.YAMLConfig) > 0) env.On("HasFiles", pulumiYAML).Return(len(tc.YAMLConfig) > 0)
env.On("FileContent", pulumiYAML).Return(tc.YAMLConfig, nil) env.On("FileContent", pulumiYAML).Return(tc.YAMLConfig, nil)
@ -210,9 +211,9 @@ description: A Console App
env.On("HasFilesInDir", filepath.Clean("/home/foobar/.pulumi/workspaces"), workspaceFile).Return(len(tc.WorkSpaceFile) > 0) env.On("HasFilesInDir", filepath.Clean("/home/foobar/.pulumi/workspaces"), workspaceFile).Return(len(tc.WorkSpaceFile) > 0)
env.On("FileContent", filepath.Clean("/home/foobar/.pulumi/workspaces/"+workspaceFile)).Return(tc.WorkSpaceFile, nil) env.On("FileContent", filepath.Clean("/home/foobar/.pulumi/workspaces/"+workspaceFile)).Return(tc.WorkSpaceFile, nil)
cache := &mock.MockedCache{} cache := &cache_.Cache{}
cache.On("Get", "pulumi-oh-my-posh-1337-c62b7b6786c5c5a85896576e46a25d7c9f888e92-about").Return(tc.AboutCache, len(tc.AboutCache) > 0) cache.On("Get", "pulumi-oh-my-posh-1337-c62b7b6786c5c5a85896576e46a25d7c9f888e92-about").Return(tc.AboutCache, len(tc.AboutCache) > 0)
cache.On("Set", mock2.Anything, mock2.Anything, mock2.Anything) cache.On("Set", testify_.Anything, testify_.Anything, testify_.Anything)
env.On("Cache").Return(cache) env.On("Cache").Return(cache)

View file

@ -5,12 +5,12 @@ import (
"path/filepath" "path/filepath"
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime" "github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/alecthomas/assert" "github.com/alecthomas/assert"
mock2 "github.com/stretchr/testify/mock" testify_ "github.com/stretchr/testify/mock"
) )
func TestPythonTemplate(t *testing.T) { func TestPythonTemplate(t *testing.T) {
@ -99,16 +99,16 @@ func TestPythonTemplate(t *testing.T) {
env, props := getMockedLanguageEnv(params) env, props := getMockedLanguageEnv(params)
env.On("GOOS").Return("") env.On("GOOS").Return("")
env.On("CommandPath", mock2.Anything).Return(tc.PythonPath) env.On("CommandPath", testify_.Anything).Return(tc.PythonPath)
env.On("RunCommand", "pyenv", []string{"version-name"}).Return(tc.VirtualEnvName, nil) env.On("RunCommand", "pyenv", []string{"version-name"}).Return(tc.VirtualEnvName, nil)
env.On("HasFilesInDir", mock2.Anything, "pyvenv.cfg").Return(len(tc.PyvenvCfg) > 0) env.On("HasFilesInDir", testify_.Anything, "pyvenv.cfg").Return(len(tc.PyvenvCfg) > 0)
env.On("FileContent", filepath.Join(filepath.Dir(tc.PythonPath), "pyvenv.cfg")).Return(tc.PyvenvCfg) env.On("FileContent", filepath.Join(filepath.Dir(tc.PythonPath), "pyvenv.cfg")).Return(tc.PyvenvCfg)
env.On("Getenv", "VIRTUAL_ENV").Return(tc.VirtualEnvName) env.On("Getenv", "VIRTUAL_ENV").Return(tc.VirtualEnvName)
env.On("Getenv", "CONDA_ENV_PATH").Return(tc.VirtualEnvName) env.On("Getenv", "CONDA_ENV_PATH").Return(tc.VirtualEnvName)
env.On("Getenv", "CONDA_DEFAULT_ENV").Return(tc.VirtualEnvName) env.On("Getenv", "CONDA_DEFAULT_ENV").Return(tc.VirtualEnvName)
env.On("Getenv", "PYENV_ROOT").Return("/home/user/.pyenv") env.On("Getenv", "PYENV_ROOT").Return("/home/user/.pyenv")
env.On("PathSeparator").Return("") env.On("PathSeparator").Return("")
env.On("ResolveSymlink", mock2.Anything).Return(tc.ResolveSymlink.Path, tc.ResolveSymlink.Err) env.On("ResolveSymlink", testify_.Anything).Return(tc.ResolveSymlink.Path, tc.ResolveSymlink.Err)
props[properties.FetchVersion] = tc.FetchVersion props[properties.FetchVersion] = tc.FetchVersion
props[UsePythonVersionFile] = true props[UsePythonVersionFile] = true
@ -131,11 +131,11 @@ func TestPythonPythonInContext(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("GOOS").Return("") env.On("GOOS").Return("")
env.On("PathSeparator").Return("/") env.On("PathSeparator").Return("/")
env.On("CommandPath", mock2.Anything).Return("") env.On("CommandPath", testify_.Anything).Return("")
env.On("HasFilesInDir", mock2.Anything, "pyvenv.cfg").Return(false) env.On("HasFilesInDir", testify_.Anything, "pyvenv.cfg").Return(false)
env.On("Getenv", "VIRTUAL_ENV").Return(tc.VirtualEnvName) env.On("Getenv", "VIRTUAL_ENV").Return(tc.VirtualEnvName)
env.On("Getenv", "CONDA_ENV_PATH").Return("") env.On("Getenv", "CONDA_ENV_PATH").Return("")
env.On("Getenv", "CONDA_DEFAULT_ENV").Return("") env.On("Getenv", "CONDA_DEFAULT_ENV").Return("")
@ -182,8 +182,8 @@ func TestPythonVirtualEnvIgnoreDefaultVenvNames(t *testing.T) {
env.On("GOOS").Return("") env.On("GOOS").Return("")
env.On("PathSeparator").Return("/") env.On("PathSeparator").Return("/")
env.On("CommandPath", mock2.Anything).Return("") env.On("CommandPath", testify_.Anything).Return("")
env.On("HasFilesInDir", mock2.Anything, "pyvenv.cfg").Return(false) env.On("HasFilesInDir", testify_.Anything, "pyvenv.cfg").Return(false)
env.On("Getenv", "VIRTUAL_ENV").Return(tc.VirtualEnvName) env.On("Getenv", "VIRTUAL_ENV").Return(tc.VirtualEnvName)
env.On("Getenv", "CONDA_ENV_PATH").Return("") env.On("Getenv", "CONDA_ENV_PATH").Return("")
env.On("Getenv", "CONDA_DEFAULT_ENV").Return("") env.On("Getenv", "CONDA_DEFAULT_ENV").Return("")

View file

@ -5,9 +5,9 @@ import (
"testing" "testing"
"github.com/alecthomas/assert" "github.com/alecthomas/assert"
"github.com/jandedobbeleer/oh-my-posh/src/mock"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime" "github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
) )
func TestSetDir(t *testing.T) { func TestSetDir(t *testing.T) {
@ -43,7 +43,7 @@ func TestSetDir(t *testing.T) {
}, },
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("GOOS").Return(tc.GOOS) env.On("GOOS").Return(tc.GOOS)
home := "/usr/home" home := "/usr/home"
if tc.GOOS == runtime.WINDOWS { if tc.GOOS == runtime.WINDOWS {
@ -100,7 +100,7 @@ func TestSetCommitContext(t *testing.T) {
}, },
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("RunCommand", "sl", []string{"log", "--limit", "1", "--template", SLCOMMITTEMPLATE}).Return(tc.Output, tc.Error) env.On("RunCommand", "sl", []string{"log", "--limit", "1", "--template", SLCOMMITTEMPLATE}).Return(tc.Output, tc.Error)
sl := &Sapling{ sl := &Sapling{
scm: scm{ scm: scm{
@ -151,7 +151,7 @@ func TestShouldDisplay(t *testing.T) {
IsDir: true, IsDir: true,
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("HasCommand", "sl").Return(tc.HasSapling) env.On("HasCommand", "sl").Return(tc.HasSapling)
env.On("InWSLSharedDrive").Return(false) env.On("InWSLSharedDrive").Return(false)
env.On("GOOS").Return(runtime.LINUX) env.On("GOOS").Return(runtime.LINUX)
@ -229,7 +229,7 @@ func TestSetHeadContext(t *testing.T) {
bm:sapling-segment bm:sapling-segment
` `
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("RunCommand", "sl", []string{"log", "--limit", "1", "--template", SLCOMMITTEMPLATE}).Return(output, nil) env.On("RunCommand", "sl", []string{"log", "--limit", "1", "--template", SLCOMMITTEMPLATE}).Return(output, nil)
env.On("RunCommand", "sl", []string{"status"}).Return(tc.Output, nil) env.On("RunCommand", "sl", []string{"status"}).Return(tc.Output, nil)
sl := &Sapling{ sl := &Sapling{

View file

@ -3,9 +3,9 @@ package segments
import ( import (
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime" "github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -195,7 +195,7 @@ func TestHasCommand(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("GOOS").Return(tc.GOOS) env.On("GOOS").Return(tc.GOOS)
env.On("InWSLSharedDrive").Return(tc.IsWslSharedPath) env.On("InWSLSharedDrive").Return(tc.IsWslSharedPath)
env.On("HasCommand", "git").Return(true) env.On("HasCommand", "git").Return(true)

View file

@ -4,9 +4,10 @@ import (
"fmt" "fmt"
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock" "github.com/jandedobbeleer/oh-my-posh/src/cache"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime" "github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -112,7 +113,7 @@ func TestSessionSegmentTemplate(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("User").Return(tc.UserName) env.On("User").Return(tc.UserName)
env.On("GOOS").Return("burp") env.On("GOOS").Return("burp")
env.On("Host").Return(tc.ComputerName, nil) env.On("Host").Return(tc.ComputerName, nil)
@ -122,7 +123,7 @@ func TestSessionSegmentTemplate(t *testing.T) {
} }
env.On("Getenv", "SSH_CONNECTION").Return(SSHSession) env.On("Getenv", "SSH_CONNECTION").Return(SSHSession)
env.On("Getenv", "SSH_CLIENT").Return(SSHSession) env.On("Getenv", "SSH_CLIENT").Return(SSHSession)
env.On("TemplateCache").Return(&runtime.TemplateCache{ env.On("TemplateCache").Return(&cache.Template{
UserName: tc.UserName, UserName: tc.UserName,
HostName: tc.ComputerName, HostName: tc.ComputerName,
Env: map[string]string{ Env: map[string]string{

View file

@ -3,16 +3,16 @@ package segments
import ( import (
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime" "github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
func TestWriteCurrentShell(t *testing.T) { func TestWriteCurrentShell(t *testing.T) {
expected := "zsh" expected := "zsh"
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("Shell").Return(expected, nil) env.On("Shell").Return(expected, nil)
env.On("Flags").Return(&runtime.Flags{ShellVersion: "1.2.3"}) env.On("Flags").Return(&runtime.Flags{ShellVersion: "1.2.3"})
s := &Shell{ s := &Shell{
@ -33,7 +33,7 @@ func TestUseMappedShellNames(t *testing.T) {
{Shell: "PWSH", Expected: "PS"}, {Shell: "PWSH", Expected: "PS"},
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("Shell").Return(tc.Expected, nil) env.On("Shell").Return(tc.Expected, nil)
env.On("Flags").Return(&runtime.Flags{ShellVersion: "1.2.3"}) env.On("Flags").Return(&runtime.Flags{ShellVersion: "1.2.3"})
s := &Shell{ s := &Shell{

View file

@ -4,8 +4,8 @@ import (
"path" "path"
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -84,7 +84,7 @@ func TestSitecoreSegment(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("HasFiles", "sitecore.json").Return(tc.SitecoreFileExists) env.On("HasFiles", "sitecore.json").Return(tc.SitecoreFileExists)
env.On("HasFiles", path.Join(".sitecore", "user.json")).Return(tc.UserFileExists) env.On("HasFiles", path.Join(".sitecore", "user.json")).Return(tc.UserFileExists)
env.On("FileContent", path.Join(".sitecore", "user.json")).Return(tc.UserFileContent) env.On("FileContent", path.Join(".sitecore", "user.json")).Return(tc.UserFileContent)

View file

@ -6,8 +6,8 @@ import (
"errors" "errors"
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -27,7 +27,7 @@ func TestSpotifyDarwinEnabledAndSpotifyPlaying(t *testing.T) {
{Running: "true", Expected: "\uF8E3 Candlemass - Spellbreaker", Status: "paused", Artist: "Candlemass", Track: "Spellbreaker"}, {Running: "true", Expected: "\uF8E3 Candlemass - Spellbreaker", Status: "paused", Artist: "Candlemass", Track: "Spellbreaker"},
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("RunCommand", "osascript", []string{"-e", "application \"Spotify\" is running"}).Return(tc.Running, tc.Error) env.On("RunCommand", "osascript", []string{"-e", "application \"Spotify\" is running"}).Return(tc.Running, tc.Error)
env.On("RunCommand", "osascript", []string{"-e", "tell application \"Spotify\" to player state as string"}).Return(tc.Status, nil) env.On("RunCommand", "osascript", []string{"-e", "tell application \"Spotify\" to player state as string"}).Return(tc.Status, nil)
env.On("RunCommand", "osascript", []string{"-e", "tell application \"Spotify\" to artist of current track as string"}).Return(tc.Artist, nil) env.On("RunCommand", "osascript", []string{"-e", "tell application \"Spotify\" to artist of current track as string"}).Return(tc.Artist, nil)

View file

@ -3,15 +3,15 @@ package segments
import ( import (
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
func TestSpotifyStringPlayingSong(t *testing.T) { func TestSpotifyStringPlayingSong(t *testing.T) {
expected := "\ue602 Candlemass - Spellbreaker" expected := "\ue602 Candlemass - Spellbreaker"
env := new(mock.MockedEnvironment) env := new(mock.Environment)
s := &Spotify{ s := &Spotify{
MusicPlayer: MusicPlayer{ MusicPlayer: MusicPlayer{
Artist: "Candlemass", Artist: "Candlemass",
@ -27,7 +27,7 @@ func TestSpotifyStringPlayingSong(t *testing.T) {
func TestSpotifyStringStoppedSong(t *testing.T) { func TestSpotifyStringStoppedSong(t *testing.T) {
expected := "\uf04d" expected := "\uf04d"
env := new(mock.MockedEnvironment) env := new(mock.Environment)
s := &Spotify{ s := &Spotify{
MusicPlayer: MusicPlayer{ MusicPlayer: MusicPlayer{
Artist: "Candlemass", Artist: "Candlemass",

View file

@ -5,9 +5,9 @@ package segments
import ( import (
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime" "github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -39,7 +39,7 @@ func TestSpotifyWindowsNative(t *testing.T) {
}, },
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("QueryWindowTitles", "spotify.exe", `^(Spotify.*)|(.*\s-\s.*)$`).Return(tc.Title, tc.Error) env.On("QueryWindowTitles", "spotify.exe", `^(Spotify.*)|(.*\s-\s.*)$`).Return(tc.Title, tc.Error)
env.On("QueryWindowTitles", "msedge.exe", `^(Spotify.*)`).Return("", &runtime.NotImplemented{}) env.On("QueryWindowTitles", "msedge.exe", `^(Spotify.*)`).Return("", &runtime.NotImplemented{})
s := &Spotify{ s := &Spotify{
@ -80,7 +80,7 @@ func TestSpotifyWindowsPWA(t *testing.T) {
}, },
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("QueryWindowTitles", "spotify.exe", "^(Spotify.*)|(.*\\s-\\s.*)$").Return("", &runtime.NotImplemented{}) env.On("QueryWindowTitles", "spotify.exe", "^(Spotify.*)|(.*\\s-\\s.*)$").Return("", &runtime.NotImplemented{})
env.On("QueryWindowTitles", "msedge.exe", "^(Spotify.*)").Return(tc.Title, tc.Error) env.On("QueryWindowTitles", "msedge.exe", "^(Spotify.*)").Return(tc.Title, tc.Error)
s := &Spotify{ s := &Spotify{

View file

@ -6,8 +6,8 @@ import (
"fmt" "fmt"
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -66,7 +66,7 @@ func TestSpotifyWsl(t *testing.T) {
}, },
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("IsWsl").Return(true) env.On("IsWsl").Return(true)
env.On("RunCommand", "tasklist.exe", []string{"/V", "/FI", "Imagename eq Spotify.exe", "/FO", "CSV", "/NH"}).Return(tc.ExecOutput, nil) env.On("RunCommand", "tasklist.exe", []string{"/V", "/FI", "Imagename eq Spotify.exe", "/FO", "CSV", "/NH"}).Return(tc.ExecOutput, nil)
s := &Spotify{ s := &Spotify{

View file

@ -3,12 +3,12 @@ package segments
import ( import (
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock" "github.com/jandedobbeleer/oh-my-posh/src/cache"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime" "github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
mock2 "github.com/stretchr/testify/mock" testify_ "github.com/stretchr/testify/mock"
) )
func TestStatusWriterEnabled(t *testing.T) { func TestStatusWriterEnabled(t *testing.T) {
@ -24,13 +24,13 @@ func TestStatusWriterEnabled(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("StatusCodes").Return(tc.Status, "") env.On("StatusCodes").Return(tc.Status, "")
env.On("TemplateCache").Return(&runtime.TemplateCache{ env.On("TemplateCache").Return(&cache.Template{
Code: 133, Code: 133,
}) })
env.On("Error", mock2.Anything).Return(nil) env.On("Error", testify_.Anything).Return(nil)
env.On("DebugF", mock2.Anything, mock2.Anything).Return(nil) env.On("DebugF", testify_.Anything, testify_.Anything).Return(nil)
props := properties.Map{} props := properties.Map{}
if len(tc.Template) > 0 { if len(tc.Template) > 0 {
@ -91,12 +91,12 @@ func TestFormatStatus(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("TemplateCache").Return(&runtime.TemplateCache{ env.On("TemplateCache").Return(&cache.Template{
Code: 133, Code: 133,
}) })
env.On("Error", mock2.Anything).Return(nil) env.On("Error", testify_.Anything).Return(nil)
env.On("DebugF", mock2.Anything, mock2.Anything).Return(nil) env.On("DebugF", testify_.Anything, testify_.Anything).Return(nil)
props := properties.Map{ props := properties.Map{
StatusTemplate: tc.Template, StatusTemplate: tc.Template,
StatusSeparator: tc.Separator, StatusSeparator: tc.Separator,

View file

@ -5,9 +5,9 @@ import (
"math" "math"
"time" "time"
"github.com/jandedobbeleer/oh-my-posh/src/http"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime" "github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/http"
) )
// StravaAPI is a wrapper around http.Oauth // StravaAPI is a wrapper around http.Oauth
@ -133,8 +133,14 @@ func (s *Strava) Init(props properties.Properties, env runtime.Environment) {
AccessTokenKey: StravaAccessTokenKey, AccessTokenKey: StravaAccessTokenKey,
RefreshTokenKey: StravaRefreshTokenKey, RefreshTokenKey: StravaRefreshTokenKey,
SegmentName: "strava", SegmentName: "strava",
AccessToken: s.props.GetString(properties.AccessToken, ""),
RefreshToken: s.props.GetString(properties.RefreshToken, ""),
Request: http.Request{
Env: env,
CacheTimeout: s.props.GetInt(properties.CacheTimeout, 30),
HTTPTimeout: s.props.GetInt(properties.HTTPTimeout, properties.DefaultHTTPTimeout),
},
} }
oauth.Init(env, props)
s.api = &stravaAPI{ s.api = &stravaAPI{
OAuthRequest: *oauth, OAuthRequest: *oauth,

View file

@ -5,15 +5,15 @@ import (
"testing" "testing"
"time" "time"
"github.com/jandedobbeleer/oh-my-posh/src/mock"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
mock2 "github.com/stretchr/testify/mock" testify_ "github.com/stretchr/testify/mock"
) )
type mockedStravaAPI struct { type mockedStravaAPI struct {
mock2.Mock testify_.Mock
} }
func (s *mockedStravaAPI) GetActivities() ([]*StravaData, error) { func (s *mockedStravaAPI) GetActivities() ([]*StravaData, error) {
@ -109,7 +109,7 @@ func TestStravaSegment(t *testing.T) {
tc.Template = strava.Template() tc.Template = strava.Template()
} }
var got = renderTemplate(&mock.MockedEnvironment{}, tc.Template, strava) var got = renderTemplate(&mock.Environment{}, tc.Template, strava)
assert.Equal(t, tc.ExpectedString, got, tc.Case) assert.Equal(t, tc.ExpectedString, got, tc.Case)
} }
} }

View file

@ -3,15 +3,15 @@ package segments
import ( import (
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime" "github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
func TestSvnEnabledToolNotFound(t *testing.T) { func TestSvnEnabledToolNotFound(t *testing.T) {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("InWSLSharedDrive").Return(false) env.On("InWSLSharedDrive").Return(false)
env.On("HasCommand", "svn").Return(false) env.On("HasCommand", "svn").Return(false)
env.On("GOOS").Return("") env.On("GOOS").Return("")
@ -31,7 +31,7 @@ func TestSvnEnabledInWorkingDirectory(t *testing.T) {
ParentFolder: "/dir", ParentFolder: "/dir",
IsDir: true, IsDir: true,
} }
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("InWSLSharedDrive").Return(false) env.On("InWSLSharedDrive").Return(false)
env.On("HasCommand", "svn").Return(true) env.On("HasCommand", "svn").Return(true)
env.On("GOOS").Return("") env.On("GOOS").Return("")
@ -157,7 +157,7 @@ func TestSvnTemplateString(t *testing.T) {
props := properties.Map{ props := properties.Map{
FetchStatus: true, FetchStatus: true,
} }
env := new(mock.MockedEnvironment) env := new(mock.Environment)
tc.Svn.env = env tc.Svn.env = env
tc.Svn.props = props tc.Svn.props = props
assert.Equal(t, tc.Expected, renderTemplate(env, tc.Template, tc.Svn), tc.Case) assert.Equal(t, tc.Expected, renderTemplate(env, tc.Template, tc.Svn), tc.Case)
@ -230,7 +230,7 @@ R Moved.File`,
ParentFolder: "/dir", ParentFolder: "/dir",
IsDir: true, IsDir: true,
} }
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("InWSLSharedDrive").Return(false) env.On("InWSLSharedDrive").Return(false)
env.On("IsWsl").Return(false) env.On("IsWsl").Return(false)
env.On("HasCommand", "svn").Return(true) env.On("HasCommand", "svn").Return(true)
@ -291,7 +291,7 @@ func TestRepo(t *testing.T) {
}, },
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("RunCommand", "svn", []string{"info", "", "--show-item", "repos-root-url"}).Return(tc.Repo, nil) env.On("RunCommand", "svn", []string{"info", "", "--show-item", "repos-root-url"}).Return(tc.Repo, nil)
s := &Svn{ s := &Svn{
scm: scm{ scm: scm{

View file

@ -4,9 +4,9 @@ import (
"errors" "errors"
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime" "github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -77,7 +77,7 @@ func TestSysInfo(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("SystemInfo").Return(&tc.SysInfo, tc.Error) env.On("SystemInfo").Return(&tc.SysInfo, tc.Error)
sysInfo := &SystemInfo{} sysInfo := &SystemInfo{}
props := properties.Map{ props := properties.Map{

View file

@ -4,9 +4,9 @@ import (
"path/filepath" "path/filepath"
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock" "github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
mock2 "github.com/stretchr/testify/mock" testify_ "github.com/stretchr/testify/mock"
) )
func TestTalosctlSegment(t *testing.T) { func TestTalosctlSegment(t *testing.T) {
@ -39,11 +39,11 @@ func TestTalosctlSegment(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("Home").Return("home") env.On("Home").Return("home")
fcPath := filepath.Join("home", ".talos", "config") fcPath := filepath.Join("home", ".talos", "config")
env.On("FileContent", fcPath).Return(tc.ActiveConfig) env.On("FileContent", fcPath).Return(tc.ActiveConfig)
env.On("Error", mock2.Anything).Return() env.On("Error", testify_.Anything).Return()
talos := TalosCTL{ talos := TalosCTL{
env: env, env: env,
} }
@ -75,12 +75,12 @@ func TestGetTalosctlActiveConfig(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("Home").Return("home") env.On("Home").Return("home")
configPath := filepath.Join("home", ".talos") configPath := filepath.Join("home", ".talos")
contentPath := filepath.Join(configPath, "config") contentPath := filepath.Join(configPath, "config")
env.On("FileContent", contentPath).Return(tc.ActiveConfig) env.On("FileContent", contentPath).Return(tc.ActiveConfig)
env.On("Error", mock2.Anything).Return() env.On("Error", testify_.Anything).Return()
talos := TalosCTL{ talos := TalosCTL{
env: env, env: env,
} }

View file

@ -4,8 +4,8 @@ import (
"os" "os"
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -82,7 +82,7 @@ func TestTerraform(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("HasCommand", "terraform").Return(tc.HasTfCommand) env.On("HasCommand", "terraform").Return(tc.HasTfCommand)
env.On("HasFolder", ".terraform").Return(tc.HasTfFolder) env.On("HasFolder", ".terraform").Return(tc.HasTfFolder)

View file

@ -3,8 +3,8 @@ package segments
import ( import (
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock" "github.com/jandedobbeleer/oh-my-posh/src/cache"
"github.com/jandedobbeleer/oh-my-posh/src/runtime" "github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -26,9 +26,9 @@ func TestTextSegment(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("PathSeparator").Return("/") env.On("PathSeparator").Return("/")
env.On("TemplateCache").Return(&runtime.TemplateCache{ env.On("TemplateCache").Return(&cache.Template{
UserName: "Posh", UserName: "Posh",
Env: map[string]string{ Env: map[string]string{
"HELLO": "hello", "HELLO": "hello",

View file

@ -5,8 +5,8 @@ import (
"testing" "testing"
"time" "time"
"github.com/jandedobbeleer/oh-my-posh/src/mock"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -41,7 +41,7 @@ func TestTimeSegmentTemplate(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
tempus := &Time{ tempus := &Time{
env: env, env: env,
props: properties.Map{}, props: properties.Map{},

View file

@ -5,7 +5,7 @@ import (
"path/filepath" "path/filepath"
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock" "github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -96,7 +96,7 @@ func TestUI5Tooling(t *testing.T) {
} }
} }
func mockFilePresence(tc *testCase, ui5tooling *UI5Tooling, env *mock.MockedEnvironment) error { func mockFilePresence(tc *testCase, ui5tooling *UI5Tooling, env *mock.Environment) error {
for _, f := range ui5tooling.language.extensions { for _, f := range ui5tooling.language.extensions {
match, err := filepath.Match(f, tc.UI5YamlFilename) match, err := filepath.Match(f, tc.UI5YamlFilename)

View file

@ -7,11 +7,11 @@ import (
"path/filepath" "path/filepath"
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock"
"github.com/jandedobbeleer/oh-my-posh/src/runtime" "github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
mock2 "github.com/stretchr/testify/mock" testify_ "github.com/stretchr/testify/mock"
) )
func TestUmbracoSegment(t *testing.T) { func TestUmbracoSegment(t *testing.T) {
@ -108,7 +108,7 @@ func TestUmbracoSegment(t *testing.T) {
for _, tc := range cases { for _, tc := range cases {
// Prepare/arrange the test // Prepare/arrange the test
env := new(mock.MockedEnvironment) env := new(mock.Environment)
var sampleCSProj, sampleWebConfig, sampleNonUmbracoCSProj string var sampleCSProj, sampleWebConfig, sampleNonUmbracoCSProj string
if tc.HasCsproj { if tc.HasCsproj {
@ -136,7 +136,7 @@ func TestUmbracoSegment(t *testing.T) {
env.On("FileContent", filepath.Join(umbracoProjectDirectory, "MyProject.csproj")).Return(sampleCSProj) env.On("FileContent", filepath.Join(umbracoProjectDirectory, "MyProject.csproj")).Return(sampleCSProj)
env.On("FileContent", filepath.Join(umbracoProjectDirectory, "ANonUmbracoProject.csproj")).Return(sampleNonUmbracoCSProj) env.On("FileContent", filepath.Join(umbracoProjectDirectory, "ANonUmbracoProject.csproj")).Return(sampleNonUmbracoCSProj)
env.On("FileContent", filepath.Join(umbracoProjectDirectory, "web.config")).Return(sampleWebConfig) env.On("FileContent", filepath.Join(umbracoProjectDirectory, "web.config")).Return(sampleWebConfig)
env.On("Debug", mock2.Anything) env.On("Debug", testify_.Anything)
if tc.HasUmbracoFolder { if tc.HasUmbracoFolder {
fileInfo := &runtime.FileInfo{ fileInfo := &runtime.FileInfo{

View file

@ -6,11 +6,12 @@ import (
"path/filepath" "path/filepath"
"testing" "testing"
mock2 "github.com/stretchr/testify/mock" testify_ "github.com/stretchr/testify/mock"
"github.com/jandedobbeleer/oh-my-posh/src/mock" cache_ "github.com/jandedobbeleer/oh-my-posh/src/cache/mock"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime" "github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -80,9 +81,9 @@ func TestUnitySegment(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("Error", mock2.Anything).Return() env.On("Error", testify_.Anything).Return()
env.On("Debug", mock2.Anything) env.On("Debug", testify_.Anything)
err := errors.New("no match at root level") err := errors.New("no match at root level")
var projectDir *runtime.FileInfo var projectDir *runtime.FileInfo
@ -215,9 +216,9 @@ func TestUnitySegmentCSharpWebRequest(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("Error", mock2.Anything).Return() env.On("Error", testify_.Anything).Return()
env.On("Debug", mock2.Anything) env.On("Debug", testify_.Anything)
err := errors.New("no match at root level") err := errors.New("no match at root level")
var projectDir *runtime.FileInfo var projectDir *runtime.FileInfo
@ -234,7 +235,7 @@ func TestUnitySegmentCSharpWebRequest(t *testing.T) {
} }
env.On("HasParentFilePath", "ProjectSettings").Return(projectDir, err) env.On("HasParentFilePath", "ProjectSettings").Return(projectDir, err)
cache := &mock.MockedCache{} cache := &cache_.Cache{}
cache.On("Get", tc.CacheGet.key).Return(tc.CacheGet.val, tc.CacheGet.found) cache.On("Get", tc.CacheGet.key).Return(tc.CacheGet.val, tc.CacheGet.found)
cache.On("Set", tc.CacheSet.key, tc.CacheSet.val, -1).Return() cache.On("Set", tc.CacheSet.key, tc.CacheSet.val, -1).Return()
env.On("Cache").Return(cache) env.On("Cache").Return(cache)

View file

@ -6,12 +6,13 @@ import (
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/build" "github.com/jandedobbeleer/oh-my-posh/src/build"
"github.com/jandedobbeleer/oh-my-posh/src/mock" cache_ "github.com/jandedobbeleer/oh-my-posh/src/cache/mock"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/jandedobbeleer/oh-my-posh/src/upgrade" "github.com/jandedobbeleer/oh-my-posh/src/upgrade"
"github.com/alecthomas/assert" "github.com/alecthomas/assert"
mock2 "github.com/stretchr/testify/mock" testify_ "github.com/stretchr/testify/mock"
) )
func TestUpgrade(t *testing.T) { func TestUpgrade(t *testing.T) {
@ -65,8 +66,8 @@ func TestUpgrade(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
cache := &mock.MockedCache{} cache := &cache_.Cache{}
env.On("Cache").Return(cache) env.On("Cache").Return(cache)
if len(tc.CachedVersion) == 0 { if len(tc.CachedVersion) == 0 {
@ -74,7 +75,7 @@ func TestUpgrade(t *testing.T) {
} }
cacheData := fmt.Sprintf(`{"latest":"%s", "current": "%s"}`, tc.LatestVersion, tc.CachedVersion) cacheData := fmt.Sprintf(`{"latest":"%s", "current": "%s"}`, tc.LatestVersion, tc.CachedVersion)
cache.On("Get", UPGRADECACHEKEY).Return(cacheData, tc.HasCache) cache.On("Get", UPGRADECACHEKEY).Return(cacheData, tc.HasCache)
cache.On("Set", mock2.Anything, mock2.Anything, mock2.Anything) cache.On("Set", testify_.Anything, testify_.Anything, testify_.Anything)
build.Version = tc.CurrentVersion build.Version = tc.CurrentVersion

View file

@ -5,12 +5,13 @@ import (
"fmt" "fmt"
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock" "github.com/jandedobbeleer/oh-my-posh/src/cache"
cache_ "github.com/jandedobbeleer/oh-my-posh/src/cache/mock"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime" "github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
mock2 "github.com/stretchr/testify/mock" testify_ "github.com/stretchr/testify/mock"
) )
func TestWTTrackedTime(t *testing.T) { func TestWTTrackedTime(t *testing.T) {
@ -72,18 +73,18 @@ func TestWTTrackedTime(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := &mock.MockedEnvironment{} env := &mock.Environment{}
response := fmt.Sprintf(`{"cumulative_total": {"seconds": %.2f, "text": "x"}}`, float64(tc.Seconds)) response := fmt.Sprintf(`{"cumulative_total": {"seconds": %.2f, "text": "x"}}`, float64(tc.Seconds))
env.On("HTTPRequest", FAKEAPIURL).Return([]byte(response), tc.Error) env.On("HTTPRequest", FAKEAPIURL).Return([]byte(response), tc.Error)
cache := &mock.MockedCache{} mockedCache := &cache_.Cache{}
cache.On("Get", FAKEAPIURL).Return(response, !tc.CacheFoundFail) mockedCache.On("Get", FAKEAPIURL).Return(response, !tc.CacheFoundFail)
cache.On("Set", FAKEAPIURL, response, tc.CacheTimeout).Return() mockedCache.On("Set", FAKEAPIURL, response, tc.CacheTimeout).Return()
env.On("Cache").Return(cache) env.On("Cache").Return(mockedCache)
env.On("DebugF", mock2.Anything, mock2.Anything).Return(nil) env.On("DebugF", testify_.Anything, testify_.Anything).Return(nil)
env.On("TemplateCache").Return(&runtime.TemplateCache{ env.On("TemplateCache").Return(&cache.Template{
Env: map[string]string{"HELLO": "hello"}, Env: map[string]string{"HELLO": "hello"},
}) })
@ -125,11 +126,11 @@ func TestWTGetUrl(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := &mock.MockedEnvironment{} env := &mock.Environment{}
env.On("Error", mock2.Anything) env.On("Error", testify_.Anything)
env.On("DebugF", mock2.Anything, mock2.Anything).Return(nil) env.On("DebugF", testify_.Anything, testify_.Anything).Return(nil)
env.On("TemplateCache").Return(&runtime.TemplateCache{ env.On("TemplateCache").Return(&cache.Template{
Env: map[string]string{"HELLO": "hello"}, Env: map[string]string{"HELLO": "hello"},
}) })

View file

@ -4,9 +4,9 @@ import (
"errors" "errors"
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime" "github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -60,7 +60,7 @@ func TestWinReg(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("GOOS").Return(runtime.WINDOWS) env.On("GOOS").Return(runtime.WINDOWS)
env.On("WindowsRegistryKeyValue", tc.Path).Return(tc.getWRKVOutput, tc.Err) env.On("WindowsRegistryKeyValue", tc.Path).Return(tc.getWRKVOutput, tc.Err)
r := &WindowsRegistry{ r := &WindowsRegistry{

View file

@ -8,11 +8,11 @@ import (
"strings" "strings"
"time" "time"
"github.com/jandedobbeleer/oh-my-posh/src/http"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime" "github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/http"
http2 "net/http" httplib "net/http"
"net/url" "net/url"
) )
@ -120,15 +120,18 @@ func (w *withingsAPI) GetSleep() (*WithingsData, error) {
} }
func (w *withingsAPI) getWithingsData(endpoint string, formData url.Values) (*WithingsData, error) { func (w *withingsAPI) getWithingsData(endpoint string, formData url.Values) (*WithingsData, error) {
modifiers := func(request *http2.Request) { modifiers := func(request *httplib.Request) {
request.Method = http2.MethodPost request.Method = httplib.MethodPost
request.Header.Add("Content-Type", "application/x-www-form-urlencoded") request.Header.Add("Content-Type", "application/x-www-form-urlencoded")
} }
body := strings.NewReader(formData.Encode()) body := strings.NewReader(formData.Encode())
data, err := http.OauthResult[*WithingsData](w.OAuthRequest, endpoint, body, modifiers) data, err := http.OauthResult[*WithingsData](w.OAuthRequest, endpoint, body, modifiers)
if data != nil && data.Status != 0 { if data != nil && data.Status != 0 {
return nil, errors.New("Withings API error: " + strconv.Itoa(data.Status)) return nil, errors.New("Withings API error: " + strconv.Itoa(data.Status))
} }
return data, err return data, err
} }
@ -207,13 +210,16 @@ func (w *Withings) getSleep() bool {
if sleepStart.IsZero() || start.Before(sleepStart) { if sleepStart.IsZero() || start.Before(sleepStart) {
sleepStart = start sleepStart = start
} }
end := time.Unix(series.Enddate, 0) end := time.Unix(series.Enddate, 0)
if sleepStart.IsZero() || start.After(sleepEnd) { if sleepStart.IsZero() || start.After(sleepEnd) {
sleepEnd = end sleepEnd = end
} }
} }
sleepHours := sleepEnd.Sub(sleepStart).Hours() sleepHours := sleepEnd.Sub(sleepStart).Hours()
w.SleepHours = fmt.Sprintf("%0.1f", sleepHours) w.SleepHours = fmt.Sprintf("%0.1f", sleepHours)
return true return true
} }
@ -224,8 +230,14 @@ func (w *Withings) Init(props properties.Properties, env runtime.Environment) {
AccessTokenKey: WithingsAccessTokenKey, AccessTokenKey: WithingsAccessTokenKey,
RefreshTokenKey: WithingsRefreshTokenKey, RefreshTokenKey: WithingsRefreshTokenKey,
SegmentName: "withings", SegmentName: "withings",
AccessToken: w.props.GetString(properties.AccessToken, ""),
RefreshToken: w.props.GetString(properties.RefreshToken, ""),
Request: http.Request{
Env: env,
CacheTimeout: w.props.GetInt(properties.CacheTimeout, 30),
HTTPTimeout: w.props.GetInt(properties.HTTPTimeout, properties.DefaultHTTPTimeout),
},
} }
oauth.Init(env, props)
w.api = &withingsAPI{ w.api = &withingsAPI{
OAuthRequest: oauth, OAuthRequest: oauth,

View file

@ -5,15 +5,15 @@ import (
"testing" "testing"
"time" "time"
"github.com/jandedobbeleer/oh-my-posh/src/mock"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
mock2 "github.com/stretchr/testify/mock" testify_ "github.com/stretchr/testify/mock"
) )
type mockedWithingsAPI struct { type mockedWithingsAPI struct {
mock2.Mock testify_.Mock
} }
func (s *mockedWithingsAPI) GetMeasures(meastypes string) (*WithingsData, error) { func (s *mockedWithingsAPI) GetMeasures(meastypes string) (*WithingsData, error) {
@ -165,7 +165,7 @@ func TestWithingsSegment(t *testing.T) {
tc.Template = withings.Template() tc.Template = withings.Template()
} }
var got = renderTemplate(&mock.MockedEnvironment{}, tc.Template, withings) var got = renderTemplate(&mock.Environment{}, tc.Template, withings)
assert.Equal(t, tc.ExpectedString, got, tc.Case) assert.Equal(t, tc.ExpectedString, got, tc.Case)
} }
} }

View file

@ -4,15 +4,15 @@ import (
"errors" "errors"
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
func bootstrapYTMDATest(json string, err error) *Ytm { func bootstrapYTMDATest(json string, err error) *Ytm {
url := "http://127.0.0.1:9863" url := "http://127.0.0.1:9863"
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("HTTPRequest", url+"/query").Return([]byte(json), err) env.On("HTTPRequest", url+"/query").Return([]byte(json), err)
ytm := &Ytm{ ytm := &Ytm{
env: env, env: env,

View file

@ -4,12 +4,12 @@ import (
"fmt" "fmt"
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/cache"
"github.com/jandedobbeleer/oh-my-posh/src/color" "github.com/jandedobbeleer/oh-my-posh/src/color"
"github.com/jandedobbeleer/oh-my-posh/src/mock" "github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
mock2 "github.com/stretchr/testify/mock" testify_ "github.com/stretchr/testify/mock"
) )
func TestConsoleBackgroundColorTemplate(t *testing.T) { func TestConsoleBackgroundColorTemplate(t *testing.T) {
@ -23,9 +23,9 @@ func TestConsoleBackgroundColorTemplate(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.Environment)
env.On("DebugF", mock2.Anything, mock2.Anything).Return(nil) env.On("DebugF", testify_.Anything, testify_.Anything).Return(nil)
env.On("TemplateCache").Return(&runtime.TemplateCache{ env.On("TemplateCache").Return(&cache.Template{
Env: map[string]string{ Env: map[string]string{
"TERM_PROGRAM": tc.Term, "TERM_PROGRAM": tc.Term,
}, },

View file

@ -3,11 +3,11 @@ package template
import ( import (
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock" "github.com/jandedobbeleer/oh-my-posh/src/cache"
"github.com/jandedobbeleer/oh-my-posh/src/runtime" "github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
mock2 "github.com/stretchr/testify/mock" testify_ "github.com/stretchr/testify/mock"
) )
func TestGlob(t *testing.T) { func TestGlob(t *testing.T) {
@ -22,9 +22,9 @@ func TestGlob(t *testing.T) {
{Case: "multiple glob", Expected: "NOK", Template: `{{ if or (glob "package.json") (glob "node_modules") }}OK{{ else }}NOK{{ end }}`}, {Case: "multiple glob", Expected: "NOK", Template: `{{ if or (glob "package.json") (glob "node_modules") }}OK{{ else }}NOK{{ end }}`},
} }
env := &mock.MockedEnvironment{} env := &mock.Environment{}
env.On("DebugF", mock2.Anything, mock2.Anything).Return(nil) env.On("DebugF", testify_.Anything, testify_.Anything).Return(nil)
env.On("TemplateCache").Return(&runtime.TemplateCache{ env.On("TemplateCache").Return(&cache.Template{
Env: make(map[string]string), Env: make(map[string]string),
}) })
for _, tc := range cases { for _, tc := range cases {

View file

@ -3,11 +3,11 @@ package template
import ( import (
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock" "github.com/jandedobbeleer/oh-my-posh/src/cache"
"github.com/jandedobbeleer/oh-my-posh/src/runtime" "github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
mock2 "github.com/stretchr/testify/mock" testify_ "github.com/stretchr/testify/mock"
) )
func TestUrl(t *testing.T) { func TestUrl(t *testing.T) {
@ -21,13 +21,13 @@ func TestUrl(t *testing.T) {
{Case: "invalid url", Expected: "", Template: `{{ url "link" "Foo" }}`, ShouldError: true}, {Case: "invalid url", Expected: "", Template: `{{ url "link" "Foo" }}`, ShouldError: true},
} }
env := &mock.MockedEnvironment{} env := &mock.Environment{}
env.On("TemplateCache").Return(&runtime.TemplateCache{ env.On("TemplateCache").Return(&cache.Template{
Env: make(map[string]string), Env: make(map[string]string),
}) })
env.On("Error", mock2.Anything) env.On("Error", testify_.Anything)
env.On("Debug", mock2.Anything) env.On("Debug", testify_.Anything)
env.On("DebugF", mock2.Anything, mock2.Anything).Return(nil) env.On("DebugF", testify_.Anything, testify_.Anything).Return(nil)
for _, tc := range cases { for _, tc := range cases {
tmpl := &Text{ tmpl := &Text{
Template: tc.Template, Template: tc.Template,
@ -52,9 +52,9 @@ func TestPath(t *testing.T) {
{Case: "valid path", Expected: "<LINK>file:/test/test<TEXT>link</TEXT></LINK>", Template: `{{ path "link" "/test/test" }}`}, {Case: "valid path", Expected: "<LINK>file:/test/test<TEXT>link</TEXT></LINK>", Template: `{{ path "link" "/test/test" }}`},
} }
env := &mock.MockedEnvironment{} env := &mock.Environment{}
env.On("DebugF", mock2.Anything, mock2.Anything).Return(nil) env.On("DebugF", testify_.Anything, testify_.Anything).Return(nil)
env.On("TemplateCache").Return(&runtime.TemplateCache{ env.On("TemplateCache").Return(&cache.Template{
Env: make(map[string]string), Env: make(map[string]string),
}) })
for _, tc := range cases { for _, tc := range cases {

View file

@ -3,11 +3,11 @@ package template
import ( import (
"testing" "testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock" "github.com/jandedobbeleer/oh-my-posh/src/cache"
"github.com/jandedobbeleer/oh-my-posh/src/runtime" "github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
mock2 "github.com/stretchr/testify/mock" testify_ "github.com/stretchr/testify/mock"
) )
func TestHResult(t *testing.T) { func TestHResult(t *testing.T) {
@ -21,13 +21,13 @@ func TestHResult(t *testing.T) {
{Case: "Not a number", Template: `{{ hresult "no number" }}`, ShouldError: true}, {Case: "Not a number", Template: `{{ hresult "no number" }}`, ShouldError: true},
} }
env := &mock.MockedEnvironment{} env := &mock.Environment{}
env.On("TemplateCache").Return(&runtime.TemplateCache{ env.On("TemplateCache").Return(&cache.Template{
Env: make(map[string]string), Env: make(map[string]string),
}) })
env.On("Error", mock2.Anything) env.On("Error", testify_.Anything)
env.On("Debug", mock2.Anything) env.On("Debug", testify_.Anything)
env.On("DebugF", mock2.Anything, mock2.Anything).Return(nil) env.On("DebugF", testify_.Anything, testify_.Anything).Return(nil)
for _, tc := range cases { for _, tc := range cases {
tmpl := &Text{ tmpl := &Text{
Template: tc.Template, Template: tc.Template,

Some files were not shown because too many files have changed in this diff Show more