-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdata_test.go
More file actions
386 lines (327 loc) · 12.5 KB
/
Copy pathdata_test.go
File metadata and controls
386 lines (327 loc) · 12.5 KB
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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
package main
import (
"os"
"path/filepath"
"regexp"
"strings"
"testing"
"time"
"github.com/bbondy/go-brianbondy/data"
"github.com/stretchr/testify/assert"
)
func TestSanitizeMarkdownHTML(t *testing.T) {
assert.True(t, safeInlineStyle.MatchString("float:left;padding-right:10px;padding-bottom:10px"))
input := `<p class="intro" style="width:90vw">Safe content</p><img src="/static/img/test.webp" style="float:left;padding-right:10px;padding-bottom:10px" onerror="alert(1)"><script>alert(1)</script><a href="javascript:alert(1)">bad link</a><iframe src="https://evil.example/embed"></iframe><iframe src="https://www.youtube.com/embed/abc123" width="320" height="560" frameborder="0" allowfullscreen></iframe><video controls><source src="/static/img/blogpost_183/video.mp4" type="video/mp4"></video>`
got := sanitizeMarkdownHTML(input)
assert.Contains(t, got, `<p class="intro" style="width:90vw">Safe content</p>`)
assert.Contains(t, got, `<img src="/static/img/test.webp" style="float:left;padding-right:10px;padding-bottom:10px">`)
assert.Contains(t, got, `<iframe src="https://www.youtube.com/embed/abc123" width="320" height="560" frameborder="0" allowfullscreen=""></iframe>`)
assert.Contains(t, got, `<video controls=""><source src="/static/img/blogpost_183/video.mp4" type="video/mp4"></video>`)
assert.NotContains(t, got, "<script")
assert.NotContains(t, got, "onerror")
assert.NotContains(t, got, "javascript:")
assert.NotContains(t, got, "evil.example")
}
func TestMarkdownSanitizationPreservesExistingMedia(t *testing.T) {
originalMarkdownMap := markdownMap
defer func() { markdownMap = originalMarkdownMap }()
markdownMap = make(map[string]string)
blogWithVideo := getMarkdownData("blog/183.markdown")
assert.Contains(t, blogWithVideo, `<img style="width:90vw" src="/static/img/blogpost_183/family-finish.webp">`)
assert.Contains(t, blogWithVideo, `<video controls="">`)
assert.Contains(t, blogWithVideo, `<source src="/static/img/blogpost_183/video.mp4" type="video/mp4">`)
blogWithEmbed := getMarkdownData("blog/190.markdown")
assert.Contains(t, blogWithEmbed, `<iframe src="https://www.youtube.com/embed/oaEKb0UJ-U8" width="320" height="560" frameborder="0" allowfullscreen=""></iframe>`)
}
func TestAllBlogMarkdownSurvivesSanitization(t *testing.T) {
files, err := filepath.Glob("data/markdown/blog/*.markdown")
if err != nil {
t.Fatalf("find blog Markdown files: %v", err)
}
if len(files) == 0 {
t.Fatal("no blog Markdown files found")
}
for _, file := range files {
content, err := os.ReadFile(file)
if err != nil {
t.Fatalf("read %s: %v", file, err)
}
rendered := renderMarkdown(content)
sanitized := sanitizeMarkdownHTML(rendered)
visibleRendered := regexp.MustCompile(`(?s)<!--.*?-->`).ReplaceAllString(rendered, "")
for _, marker := range []string{"style=", "class=", "<video", "<iframe"} {
if strings.Count(sanitized, marker) != strings.Count(visibleRendered, marker) {
t.Errorf("%s: sanitizer changed %q count from %d to %d", file, marker, strings.Count(visibleRendered, marker), strings.Count(sanitized, marker))
}
}
if strings.Contains(sanitized, "<script") {
t.Errorf("%s: sanitized output contains a script tag", file)
}
if regexp.MustCompile(`(?i)\son[a-z]+\s*=`).MatchString(sanitized) {
t.Errorf("%s: sanitized output contains an event handler", file)
}
}
}
// TestDerefString tests the derefString helper function
func TestDerefString(t *testing.T) {
// Test with nil pointer
result := derefString(nil)
assert.Equal(t, "", result, "derefString(nil) should return empty string")
// Test with non-nil pointer
value := "test string"
result = derefString(&value)
assert.Equal(t, value, result, "derefString should return the string value")
}
// TestGetFilteredPosts tests filtering by tag, year, or both
func TestGetFilteredPosts(t *testing.T) {
// Save original data
origBlogPosts := blogPosts
origBlogPostTagMap := blogPostTagMap
origBlogPostYearMap := blogPostYearMap
// Restore after test
defer func() {
blogPosts = origBlogPosts
blogPostTagMap = origBlogPostTagMap
blogPostYearMap = origBlogPostYearMap
}()
// Setup test data
setupTestData()
// Test case 1: No filters (should return all posts)
posts := getFilteredPosts("", 0)
assert.Len(t, posts, 3, "With no filters, should return all posts")
// Test case 2: Filter by tag only
posts = getFilteredPosts("golang", 0)
assert.Len(t, posts, 2, "Should return posts with 'golang' tag")
// Test case 3: Filter by year only
posts = getFilteredPosts("", 2022)
assert.Len(t, posts, 1, "Should return posts from 2022")
// Test case 4: Filter by both tag and year
posts = getFilteredPosts("golang", 2022)
assert.Len(t, posts, 1, "Should return posts with 'golang' tag from 2022")
// Test case 5: Filter with no matching posts
posts = getFilteredPosts("nonexistent", 0)
assert.Len(t, posts, 0, "Should return empty slice for non-existent tag")
}
// TestGetMarkdownData tests the markdown parsing and caching
func TestGetMarkdownData(t *testing.T) {
// Save original markdownMap
origMarkdownMap := markdownMap
// Restore after test
defer func() {
markdownMap = origMarkdownMap
}()
// Reset the markdown map
markdownMap = make(map[string]string)
// Pre-populate the cache with rendered content
markdownMap["test.md"] = "<h1>Test Heading</h1>\n<p>This is a test paragraph.</p>"
// Test first call (should read from cache)
html := getMarkdownData("test.md")
assert.Contains(t, html, "<h1", "Markdown should be converted to HTML")
assert.Contains(t, html, "Test Heading", "HTML should contain the heading text")
assert.Contains(t, html, "<p>This is a test paragraph.</p>", "HTML should contain the paragraph")
// Test second call (should read from cache again)
html2 := getMarkdownData("test.md")
assert.Equal(t, html, html2, "Second call should return cached content")
// Add another entry to the cache
markdownMap["test2.md"] = "<h2>Another Test</h2>"
// Test with the new entry
html3 := getMarkdownData("test2.md")
assert.Contains(t, html3, "<h2", "Should read new content")
assert.Contains(t, html3, "Another Test", "HTML should contain the content from the new file")
}
func TestPrimeSiteData(t *testing.T) {
origMarkdownMap := markdownMap
defer func() { markdownMap = origMarkdownMap }()
data.ClearProjectsCache()
data.ClearInterviewsCache()
data.ClearBooksCache()
data.ClearRunsCache()
data.ClearStravaRunsCache()
data.ClearCheatsheetsCache()
ClearPicturesCache()
markdownMap = make(map[string]string)
assert.NoError(t, primeSiteData())
assert.NotEmpty(t, markdownMap["about.markdown"])
assert.NotEmpty(t, markdownMap["cheatsheets/go.md"])
assert.True(t, picturesLoaded)
}
// TestGetProjectsCaching tests the caching mechanism for GetProjects
func TestGetProjectsCaching(t *testing.T) {
// Clear cache before test
data.ClearProjectsCache()
// First call should load from file
projects1, err1 := data.GetProjects()
assert.NoError(t, err1)
assert.NotEmpty(t, projects1)
// Second call should return cached data (same pointer to first element)
projects2, err2 := data.GetProjects()
assert.NoError(t, err2)
assert.NotEmpty(t, projects2)
assert.True(t, &projects1[0] == &projects2[0], "Should return the same cached data instance (element pointer)")
// Clear cache and reload
data.ClearProjectsCache()
projects3, err3 := data.GetProjects()
assert.NoError(t, err3)
assert.NotEmpty(t, projects3)
assert.False(t, &projects2[0] == &projects3[0], "After clearing cache, should reload from file (different element pointer)")
}
func TestProjectsManifestIncludesBraveDevBotEmoji(t *testing.T) {
data.ClearProjectsCache()
projects, err := data.GetProjects()
assert.NoError(t, err)
found := false
for _, project := range projects {
if project.Github != "https://github.com/brave-experiments/brave-dev-bot" {
continue
}
found = true
assert.Equal(t, "Brave Dev Bot", project.Title)
assert.Equal(t, "🤖", project.Emoji)
assert.Equal(t, "https://github.com/brave-experiments/brave-dev-bot", project.URL)
}
assert.True(t, found, "Brave Dev Bot project should exist in the manifest")
}
// TestGetCheatsheetsCaching tests the caching mechanism for GetCheatsheets
func TestGetCheatsheetsCaching(t *testing.T) {
// Clear cache before test
data.ClearCheatsheetsCache()
// First call should load from file
cheatsheets1, err1 := data.GetCheatsheets()
assert.NoError(t, err1)
assert.NotEmpty(t, cheatsheets1)
// Second call should return cached data (same pointer to first element)
cheatsheets2, err2 := data.GetCheatsheets()
assert.NoError(t, err2)
assert.NotEmpty(t, cheatsheets2)
assert.True(t, &cheatsheets1[0] == &cheatsheets2[0], "Should return the same cached data instance (element pointer)")
// Clear cache and reload
data.ClearCheatsheetsCache()
cheatsheets3, err3 := data.GetCheatsheets()
assert.NoError(t, err3)
assert.NotEmpty(t, cheatsheets3)
assert.False(t, &cheatsheets2[0] == &cheatsheets3[0], "After clearing cache, should reload from file (different element pointer)")
}
// Helper function to set up test data
func setupTestData() {
// Reset all the global variables
blogPosts = []data.BlogPost{
{
Id: 1,
Title: "Test Post 1",
Created: "2023-01-01",
Tags: []string{"test", "golang"},
},
{
Id: 2,
Title: "Test Post 2",
Created: "2023-02-01",
Tags: []string{"test"},
},
{
Id: 3,
Title: "Test Post 3",
Created: "2022-01-01",
Tags: []string{"golang"},
},
}
// Setup blog post ID map
blogPostIdMap = make(map[int]data.BlogPost)
for _, post := range blogPosts {
blogPostIdMap[post.Id] = post
}
// Setup tag maps
blogPostTagMap = make(map[string][]data.BlogPost)
tagCountMap = make(map[string]int)
for _, post := range blogPosts {
for _, tag := range post.Tags {
blogPostTagMap[tag] = append(blogPostTagMap[tag], post)
tagCountMap[tag]++
}
}
// Setup year map
blogPostYearMap = make(map[int][]data.BlogPost)
for _, post := range blogPosts {
parsedDate, _ := time.Parse(layoutISO, post.Created)
year := parsedDate.Year()
blogPostYearMap[year] = append(blogPostYearMap[year], post)
}
// Setup sorted tags
sortedTags = []string{"test", "golang"}
}
// TestMockInitializeBlogPosts tests the blog post initialization logic
// but uses a mock approach instead of actual file reading
func TestMockInitializeBlogPosts(t *testing.T) {
// Save original data
origBlogPosts := blogPosts
origBlogPostIdMap := blogPostIdMap
origBlogPostTagMap := blogPostTagMap
origBlogPostYearMap := blogPostYearMap
origTagCountMap := tagCountMap
origSortedTags := sortedTags
// Restore after test
defer func() {
blogPosts = origBlogPosts
blogPostIdMap = origBlogPostIdMap
blogPostTagMap = origBlogPostTagMap
blogPostYearMap = origBlogPostYearMap
tagCountMap = origTagCountMap
sortedTags = origSortedTags
}()
// Reset global variables
blogPosts = nil
blogPostIdMap = make(map[int]data.BlogPost)
blogPostTagMap = make(map[string][]data.BlogPost)
blogPostYearMap = make(map[int][]data.BlogPost)
tagCountMap = make(map[string]int)
sortedTags = nil
// Manually call the setup that initializeBlogPosts would do
blogPosts = []data.BlogPost{
{
Id: 1,
Title: "Test Post 1",
Created: "2023-01-01",
Tags: []string{"test", "golang"},
},
{
Id: 2,
Title: "Test Post 2",
Created: "2023-02-01",
Tags: []string{"test"},
},
{
Id: 3,
Title: "Test Post 3",
Created: "2022-01-01",
Tags: []string{"golang"},
},
}
// Process the posts as initializeBlogPosts would
for _, blogPost := range blogPosts {
for _, tag := range blogPost.Tags {
blogPostTagMap[tag] = append(blogPostTagMap[tag], blogPost)
tagCountMap[tag] += 1
}
parsedDate, _ := time.Parse(layoutISO, blogPost.Created)
year := parsedDate.Year()
blogPostYearMap[year] = append(blogPostYearMap[year], blogPost)
blogPostIdMap[blogPost.Id] = blogPost
}
sortedTags = make([]string, len(tagCountMap))
i := 0
for k := range tagCountMap {
sortedTags[i] = k
i++
}
// Verify results
assert.Len(t, blogPosts, 3, "Should load 3 blog posts")
assert.Len(t, blogPostIdMap, 3, "Should create ID map with 3 entries")
assert.Len(t, blogPostTagMap, 2, "Should create tag map with 2 entries (test, golang)")
assert.Len(t, blogPostYearMap, 2, "Should create year map with 2 entries (2022, 2023)")
// Check tag counts
assert.Equal(t, 2, tagCountMap["test"], "Tag 'test' should appear 2 times")
assert.Equal(t, 2, tagCountMap["golang"], "Tag 'golang' should appear 2 times")
// Check sorted tags
assert.Len(t, sortedTags, 2, "Should have 2 sorted tags")
assert.Contains(t, sortedTags, "test")
assert.Contains(t, sortedTags, "golang")
}