]> Sergey Matveev's repositories - btrtrc.git/blob - storage/safe-path_test.go
Fix unit tests littering working directory
[btrtrc.git] / storage / safe-path_test.go
1 package storage
2
3 import (
4         "fmt"
5         "log"
6         "path/filepath"
7         "testing"
8
9         "github.com/anacrolix/torrent/metainfo"
10         qt "github.com/frankban/quicktest"
11 )
12
13 func init() {
14         log.SetFlags(log.Flags() | log.Lshortfile)
15 }
16
17 // I think these are mainly tests for bad metainfos that try to escape the client base directory.
18 var safeFilePathTests = []struct {
19         input     []string
20         expectErr bool
21 }{
22         // We might want a test for invalid chars inside components, or file maker opt funcs returning
23         // absolute paths (and thus presumably clobbering earlier "makers").
24         {input: []string{"a", filepath.FromSlash(`b/..`)}, expectErr: false},
25         {input: []string{"a", filepath.FromSlash(`b/../../..`)}, expectErr: true},
26         {input: []string{"a", filepath.FromSlash(`b/../.././..`)}, expectErr: true},
27         {input: []string{
28                 filepath.FromSlash(`NewSuperHeroMovie-2019-English-720p.avi /../../../../../Roaming/Microsoft/Windows/Start Menu/Programs/Startup/test3.exe`)},
29                 expectErr: true,
30         },
31 }
32
33 // Tests the ToSafeFilePath func.
34 func TestToSafeFilePath(t *testing.T) {
35         for _, _case := range safeFilePathTests {
36                 actual, err := ToSafeFilePath(_case.input...)
37                 if _case.expectErr {
38                         if err != nil {
39                                 continue
40                         }
41                         t.Errorf("%q: expected error, got output %q", _case.input, actual)
42                 }
43         }
44 }
45
46 // Check that safe file path handling still exists for the newer file-opt-maker variants.
47 func TestFileOptsSafeFilePathHandling(t *testing.T) {
48         c := qt.New(t)
49         for i, _case := range safeFilePathTests {
50                 c.Run(fmt.Sprintf("Case%v", i), func(c *qt.C) {
51                         info := metainfo.Info{
52                                 Files: []metainfo.FileInfo{
53                                         {Path: _case.input},
54                                 },
55                         }
56                         client := NewFileOpts(NewFileClientOpts{
57                                 ClientBaseDir: t.TempDir(),
58                         })
59                         defer func() { c.Check(client.Close(), qt.IsNil) }()
60                         torImpl, err := client.OpenTorrent(&info, metainfo.Hash{})
61                         if _case.expectErr {
62                                 c.Check(err, qt.Not(qt.IsNil))
63                         } else {
64                                 c.Check(torImpl.Close(), qt.IsNil)
65                         }
66                 })
67         }
68 }