aboutsummaryrefslogtreecommitdiff
path: root/cmd/mobius-hotline-server/main_test.go
blob: 827397a6fe789fbbe0b38bb4c980ebe9c1e07896 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
package main

import (
	"context"
	"os"
	"path"
	"testing"

	"github.com/jhalter/mobius/internal/mobius"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func TestCopyDir(t *testing.T) {
	// Test using the actual embedded config directory
	dstDir := t.TempDir()

	// Execute copyDir with the embedded mobius/config directory
	err := copyDir("mobius/config", dstDir)
	require.NoError(t, err)

	// Verify some expected files exist (based on the embedded config)
	expectedFiles := []string{
		"config.yaml",
		"Agreement.txt",
		"MessageBoard.txt",
		"ThreadedNews.yaml",
		"Users/admin.yaml",
		"Users/guest.yaml",
		"banner.jpg",
	}

	for _, expectedFile := range expectedFiles {
		fullPath := path.Join(dstDir, expectedFile)
		assert.FileExists(t, fullPath, "Expected file %s to exist", expectedFile)

		// Verify file is not empty
		info, err := os.Stat(fullPath)
		require.NoError(t, err)
		assert.Greater(t, info.Size(), int64(0), "File %s should not be empty", expectedFile)
	}

	// Verify directories were created
	expectedDirs := []string{
		"Users",
		"Files",
	}

	for _, expectedDir := range expectedDirs {
		fullPath := path.Join(dstDir, expectedDir)
		info, err := os.Stat(fullPath)
		require.NoError(t, err)
		assert.True(t, info.IsDir(), "Expected %s to be a directory", expectedDir)
	}
}

func TestCopyDirNonexistentSource(t *testing.T) {
	dstDir := t.TempDir()

	err := copyDir("nonexistent/directory", dstDir)
	assert.Error(t, err)
	assert.Contains(t, err.Error(), "failed to read source directory")
}

func TestCopyDirRecursive(t *testing.T) {
	// Test the recursive functionality using embedded config
	dstDir := t.TempDir()

	err := copyDirRecursive("mobius/config", dstDir)
	require.NoError(t, err)

	// Verify nested structure is copied correctly
	nestedPath := path.Join(dstDir, "Users", "admin.yaml")
	assert.FileExists(t, nestedPath)

	// Verify nested Files directory
	filesDir := path.Join(dstDir, "Files")
	info, err := os.Stat(filesDir)
	require.NoError(t, err)
	assert.True(t, info.IsDir())
}

func TestCopyFile(t *testing.T) {
	dstDir := t.TempDir()
	dstFile := path.Join(dstDir, "copied.yaml")

	// Copy a single file from embedded config
	err := copyFile("mobius/config/config.yaml", dstFile)
	require.NoError(t, err)

	// Verify file was copied correctly
	assert.FileExists(t, dstFile)

	// Verify file is not empty
	info, err := os.Stat(dstFile)
	require.NoError(t, err)
	assert.Greater(t, info.Size(), int64(0))
}

func TestCopyFileErrors(t *testing.T) {
	t.Run("source file does not exist", func(t *testing.T) {
		dstDir := t.TempDir()
		err := copyFile("nonexistent.txt", path.Join(dstDir, "dest.txt"))
		assert.Error(t, err)
		assert.Contains(t, err.Error(), "failed to open source file")
	})

	t.Run("destination directory does not exist", func(t *testing.T) {
		err := copyFile("mobius/config/config.yaml", "/nonexistent/directory/dest.txt")
		assert.Error(t, err)
		assert.Contains(t, err.Error(), "failed to create destination file")
	})
}

func TestCopyDirPermissions(t *testing.T) {
	dstDir := t.TempDir()

	err := copyDir("mobius/config", dstDir)
	require.NoError(t, err)

	// Check directory permissions
	info, err := os.Stat(path.Join(dstDir, "Users"))
	require.NoError(t, err)
	assert.True(t, info.IsDir())

	// Check that directory has reasonable permissions (at least readable/executable)
	mode := info.Mode()
	assert.True(t, mode&0400 != 0, "Directory should be readable")
	assert.True(t, mode&0100 != 0, "Directory should be executable")
}

func TestFindConfigPath(t *testing.T) {
	// Test function behavior by checking it returns one of the expected paths or fallback
	t.Run("returns valid path", func(t *testing.T) {
		result := findConfigPath()

		// Should return either one of the search paths that exists, or "config" fallback
		validPaths := append([]string{"config"}, mobius.ConfigSearchOrder...)

		found := false
		for _, validPath := range validPaths {
			if result == validPath {
				found = true
				break
			}
		}

		assert.True(t, found, "findConfigPath should return one of the valid paths or fallback, got: %s", result)
	})

	// Test directory vs file validation
	t.Run("validates directory vs file", func(t *testing.T) {
		// This test verifies the function logic but can't control system directories
		// The function correctly validates that only directories are returned
		result := findConfigPath()

		// Verify result is an actual directory if it exists
		if result != "config" {
			info, err := os.Stat(result)
			require.NoError(t, err, "Returned path should exist")
			assert.True(t, info.IsDir(), "Returned path should be a directory")
		}
	})

	// Test with existing directory
	t.Run("finds existing directory", func(t *testing.T) {
		tmpDir := t.TempDir()
		originalDir, err := os.Getwd()
		require.NoError(t, err)
		defer func() { _ = os.Chdir(originalDir) }()

		err = os.Chdir(tmpDir)
		require.NoError(t, err)

		// Create a config directory
		err = os.Mkdir("config", 0755)
		require.NoError(t, err)

		result := findConfigPath()
		assert.Equal(t, "config", result)
	})
}

// r2EnvVars are every R2_* variable newR2FileStore reads. Each case clears all of them and sets
// only what it needs, so ambient credentials in the test environment can't leak in.
var r2EnvVars = []string{
	"R2_BUCKET", "R2_ACCESS_KEY_ID", "R2_SECRET_ACCESS_KEY",
	"R2_ENDPOINT", "R2_ACCOUNT_ID", "R2_PREFIX", "R2_STAGING_DIR",
}

func TestNewR2FileStore_EnvValidation(t *testing.T) {
	tests := []struct {
		name    string
		env     map[string]string
		wantErr string // substring; empty means the store must construct successfully
	}{
		{
			name:    "missing bucket and credentials",
			env:     map[string]string{},
			wantErr: "R2_BUCKET, R2_ACCESS_KEY_ID, and R2_SECRET_ACCESS_KEY must be set",
		},
		{
			name: "missing secret key",
			env: map[string]string{
				"R2_BUCKET":        "b",
				"R2_ACCESS_KEY_ID": "ak",
			},
			wantErr: "R2_BUCKET, R2_ACCESS_KEY_ID, and R2_SECRET_ACCESS_KEY must be set",
		},
		{
			name: "credentials set but no endpoint or account id",
			env: map[string]string{
				"R2_BUCKET":            "b",
				"R2_ACCESS_KEY_ID":     "ak",
				"R2_SECRET_ACCESS_KEY": "sk",
			},
			wantErr: "either R2_ENDPOINT or R2_ACCOUNT_ID must be set",
		},
		{
			name: "account id derives the endpoint",
			env: map[string]string{
				"R2_BUCKET":            "b",
				"R2_ACCESS_KEY_ID":     "ak",
				"R2_SECRET_ACCESS_KEY": "sk",
				"R2_ACCOUNT_ID":        "acct123",
			},
		},
		{
			name: "explicit endpoint",
			env: map[string]string{
				"R2_BUCKET":            "b",
				"R2_ACCESS_KEY_ID":     "ak",
				"R2_SECRET_ACCESS_KEY": "sk",
				"R2_ENDPOINT":          "https://example.com",
			},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			for _, k := range r2EnvVars {
				t.Setenv(k, "")
			}
			// Keep staging off the shared temp dir even on the success paths.
			t.Setenv("R2_STAGING_DIR", t.TempDir())
			for k, v := range tt.env {
				t.Setenv(k, v)
			}

			store, err := newR2FileStore(context.Background())
			if tt.wantErr != "" {
				require.Error(t, err)
				assert.Contains(t, err.Error(), tt.wantErr)
				assert.Nil(t, store)
				return
			}
			require.NoError(t, err)
			assert.NotNil(t, store)
		})
	}
}