]> git.giacomolli.uk - onechat/blob - datadir_test.go
Import WhatsApp history into a child
[onechat] / datadir_test.go
1 package main
2
3 import (
4         "os"
5         "path/filepath"
6         "testing"
7
8         "github.com/stretchr/testify/require"
9 )
10
11 func TestDataDirFollowsTheOrder(t *testing.T) {
12         root := t.TempDir()
13         testCases := []struct {
14                 name string
15                 dir  string
16                 xdg  string
17                 home string
18                 want string
19         }{
20                 {
21                         name: "ONECHAT_DIR first",
22                         dir:  filepath.Join(root, "a"),
23                         xdg:  filepath.Join(root, "xdg"),
24                         home: root,
25                         want: filepath.Join(root, "a"),
26                 },
27                 {
28                         name: "absolute XDG_DATA_HOME",
29                         dir:  "",
30                         xdg:  filepath.Join(root, "xdg"),
31                         home: root,
32                         want: filepath.Join(root, "xdg", "onechat"),
33                 },
34                 {
35                         name: "relative XDG_DATA_HOME ignored",
36                         dir:  "",
37                         xdg:  "xdg",
38                         home: root,
39                         want: filepath.Join(root, ".local", "share", "onechat"),
40                 },
41                 {
42                         name: "home directory last",
43                         dir:  "",
44                         xdg:  "",
45                         home: root,
46                         want: filepath.Join(root, ".local", "share", "onechat"),
47                 },
48         }
49
50         for _, tc := range testCases {
51                 t.Run(tc.name, func(t *testing.T) {
52                         t.Setenv("ONECHAT_DIR", tc.dir)
53                         t.Setenv("XDG_DATA_HOME", tc.xdg)
54                         t.Setenv("HOME", tc.home)
55
56                         dir, err := dataDir()
57                         require.NoError(t, err)
58                         require.Equal(t, tc.want, dir)
59
60                         info, err := os.Stat(dir)
61                         require.NoError(t, err)
62                         require.Equal(t, os.FileMode(0o700), info.Mode().Perm())
63                 })
64         }
65 }
66
67 func TestDataDirFailsWithoutAHome(t *testing.T) {
68         t.Setenv("ONECHAT_DIR", "")
69         t.Setenv("XDG_DATA_HOME", "")
70         t.Setenv("HOME", "")
71
72         _, err := dataDir()
73         require.ErrorContains(t, err, "ONECHAT_DIR")
74 }