testutils_test.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. // Copyright (C) 2016 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package model
  7. import (
  8. "context"
  9. "io/ioutil"
  10. "os"
  11. "testing"
  12. "time"
  13. "github.com/syncthing/syncthing/lib/config"
  14. "github.com/syncthing/syncthing/lib/db"
  15. "github.com/syncthing/syncthing/lib/db/backend"
  16. "github.com/syncthing/syncthing/lib/events"
  17. "github.com/syncthing/syncthing/lib/fs"
  18. "github.com/syncthing/syncthing/lib/ignore"
  19. "github.com/syncthing/syncthing/lib/protocol"
  20. "github.com/syncthing/syncthing/lib/rand"
  21. )
  22. var (
  23. myID, device1, device2 protocol.DeviceID
  24. defaultCfgWrapper config.Wrapper
  25. defaultFolderConfig config.FolderConfiguration
  26. defaultFs fs.Filesystem
  27. defaultCfg config.Configuration
  28. defaultAutoAcceptCfg config.Configuration
  29. )
  30. func init() {
  31. myID, _ = protocol.DeviceIDFromString("ZNWFSWE-RWRV2BD-45BLMCV-LTDE2UR-4LJDW6J-R5BPWEB-TXD27XJ-IZF5RA4")
  32. device1, _ = protocol.DeviceIDFromString("AIR6LPZ-7K4PTTV-UXQSMUU-CPQ5YWH-OEDFIIQ-JUG777G-2YQXXR5-YD6AWQR")
  33. device2, _ = protocol.DeviceIDFromString("GYRZZQB-IRNPV4Z-T7TC52W-EQYJ3TT-FDQW6MW-DFLMU42-SSSU6EM-FBK2VAY")
  34. defaultFolderConfig = testFolderConfig("testdata")
  35. defaultFs = defaultFolderConfig.Filesystem()
  36. defaultCfgWrapper = createTmpWrapper(config.New(myID))
  37. _, _ = defaultCfgWrapper.SetDevice(config.NewDeviceConfiguration(device1, "device1"))
  38. _, _ = defaultCfgWrapper.SetFolder(defaultFolderConfig)
  39. opts := defaultCfgWrapper.Options()
  40. opts.KeepTemporariesH = 1
  41. _, _ = defaultCfgWrapper.SetOptions(opts)
  42. defaultCfg = defaultCfgWrapper.RawCopy()
  43. defaultAutoAcceptCfg = config.Configuration{
  44. Version: config.CurrentVersion,
  45. Devices: []config.DeviceConfiguration{
  46. {
  47. DeviceID: myID, // self
  48. },
  49. {
  50. DeviceID: device1,
  51. AutoAcceptFolders: true,
  52. },
  53. {
  54. DeviceID: device2,
  55. AutoAcceptFolders: true,
  56. },
  57. },
  58. Options: config.OptionsConfiguration{
  59. DefaultFolderPath: ".",
  60. },
  61. }
  62. }
  63. func tmpDefaultWrapper() (config.Wrapper, config.FolderConfiguration) {
  64. w := createTmpWrapper(defaultCfgWrapper.RawCopy())
  65. fcfg := testFolderConfigTmp()
  66. _, _ = w.SetFolder(fcfg)
  67. return w, fcfg
  68. }
  69. func testFolderConfigTmp() config.FolderConfiguration {
  70. tmpDir := createTmpDir()
  71. return testFolderConfig(tmpDir)
  72. }
  73. func testFolderConfig(path string) config.FolderConfiguration {
  74. cfg := config.NewFolderConfiguration(myID, "default", "default", fs.FilesystemTypeBasic, path)
  75. cfg.FSWatcherEnabled = false
  76. cfg.Devices = append(cfg.Devices, config.FolderDeviceConfiguration{DeviceID: device1})
  77. return cfg
  78. }
  79. func testFolderConfigFake() config.FolderConfiguration {
  80. cfg := config.NewFolderConfiguration(myID, "default", "default", fs.FilesystemTypeFake, rand.String(32)+"?content=true")
  81. cfg.FSWatcherEnabled = false
  82. cfg.Devices = append(cfg.Devices, config.FolderDeviceConfiguration{DeviceID: device1})
  83. return cfg
  84. }
  85. func setupModelWithConnection() (*testModel, *fakeConnection, config.FolderConfiguration) {
  86. w, fcfg := tmpDefaultWrapper()
  87. m, fc := setupModelWithConnectionFromWrapper(w)
  88. return m, fc, fcfg
  89. }
  90. func setupModelWithConnectionFromWrapper(w config.Wrapper) (*testModel, *fakeConnection) {
  91. m := setupModel(w)
  92. fc := addFakeConn(m, device1)
  93. fc.folder = "default"
  94. _ = m.ScanFolder("default")
  95. return m, fc
  96. }
  97. func setupModel(w config.Wrapper) *testModel {
  98. db := db.NewLowlevel(backend.OpenMemory())
  99. m := newModel(w, myID, "syncthing", "dev", db, nil)
  100. m.ServeBackground()
  101. <-m.started
  102. m.ScanFolders()
  103. return m
  104. }
  105. type testModel struct {
  106. *model
  107. cancel context.CancelFunc
  108. evCancel context.CancelFunc
  109. stopped chan struct{}
  110. }
  111. func newModel(cfg config.Wrapper, id protocol.DeviceID, clientName, clientVersion string, ldb *db.Lowlevel, protectedFiles []string) *testModel {
  112. evLogger := events.NewLogger()
  113. m := NewModel(cfg, id, clientName, clientVersion, ldb, protectedFiles, evLogger).(*model)
  114. ctx, cancel := context.WithCancel(context.Background())
  115. go evLogger.Serve(ctx)
  116. return &testModel{
  117. model: m,
  118. evCancel: cancel,
  119. stopped: make(chan struct{}),
  120. }
  121. }
  122. func (m *testModel) ServeBackground() {
  123. ctx, cancel := context.WithCancel(context.Background())
  124. m.cancel = cancel
  125. go func() {
  126. m.model.Serve(ctx)
  127. close(m.stopped)
  128. }()
  129. <-m.started
  130. }
  131. func cleanupModel(m *testModel) {
  132. if m.cancel != nil {
  133. m.cancel()
  134. <-m.stopped
  135. }
  136. m.evCancel()
  137. m.db.Close()
  138. os.Remove(m.cfg.ConfigPath())
  139. }
  140. func cleanupModelAndRemoveDir(m *testModel, dir string) {
  141. cleanupModel(m)
  142. os.RemoveAll(dir)
  143. }
  144. func createTmpDir() string {
  145. tmpDir, err := ioutil.TempDir("", "syncthing_testFolder-")
  146. if err != nil {
  147. panic("Failed to create temporary testing dir")
  148. }
  149. return tmpDir
  150. }
  151. type alwaysChangedKey struct {
  152. fs fs.Filesystem
  153. name string
  154. }
  155. // alwaysChanges is an ignore.ChangeDetector that always returns true on Changed()
  156. type alwaysChanged struct {
  157. seen map[alwaysChangedKey]struct{}
  158. }
  159. func newAlwaysChanged() *alwaysChanged {
  160. return &alwaysChanged{
  161. seen: make(map[alwaysChangedKey]struct{}),
  162. }
  163. }
  164. func (c *alwaysChanged) Remember(fs fs.Filesystem, name string, _ time.Time) {
  165. c.seen[alwaysChangedKey{fs, name}] = struct{}{}
  166. }
  167. func (c *alwaysChanged) Reset() {
  168. c.seen = make(map[alwaysChangedKey]struct{})
  169. }
  170. func (c *alwaysChanged) Seen(fs fs.Filesystem, name string) bool {
  171. _, ok := c.seen[alwaysChangedKey{fs, name}]
  172. return ok
  173. }
  174. func (c *alwaysChanged) Changed() bool {
  175. return true
  176. }
  177. func localSize(t *testing.T, m Model, folder string) db.Counts {
  178. t.Helper()
  179. snap := dbSnapshot(t, m, folder)
  180. defer snap.Release()
  181. return snap.LocalSize()
  182. }
  183. func globalSize(t *testing.T, m Model, folder string) db.Counts {
  184. t.Helper()
  185. snap := dbSnapshot(t, m, folder)
  186. defer snap.Release()
  187. return snap.GlobalSize()
  188. }
  189. func receiveOnlyChangedSize(t *testing.T, m Model, folder string) db.Counts {
  190. t.Helper()
  191. snap := dbSnapshot(t, m, folder)
  192. defer snap.Release()
  193. return snap.ReceiveOnlyChangedSize()
  194. }
  195. func needSize(t *testing.T, m Model, folder string) db.Counts {
  196. t.Helper()
  197. snap := dbSnapshot(t, m, folder)
  198. defer snap.Release()
  199. return snap.NeedSize(protocol.LocalDeviceID)
  200. }
  201. func dbSnapshot(t *testing.T, m Model, folder string) *db.Snapshot {
  202. t.Helper()
  203. snap, err := m.DBSnapshot(folder)
  204. if err != nil {
  205. t.Fatal(err)
  206. }
  207. return snap
  208. }
  209. // Reach in and update the ignore matcher to one that always does
  210. // reloads when asked to, instead of checking file mtimes. This is
  211. // because we will be changing the files on disk often enough that the
  212. // mtimes will be unreliable to determine change status.
  213. func folderIgnoresAlwaysReload(m *testModel, fcfg config.FolderConfiguration) {
  214. m.removeFolder(fcfg)
  215. fset := db.NewFileSet(fcfg.ID, fcfg.Filesystem(), m.db)
  216. ignores := ignore.New(fcfg.Filesystem(), ignore.WithCache(true), ignore.WithChangeDetector(newAlwaysChanged()))
  217. m.fmut.Lock()
  218. m.addAndStartFolderLockedWithIgnores(fcfg, fset, ignores)
  219. m.fmut.Unlock()
  220. }
  221. func basicClusterConfig(local, remote protocol.DeviceID, folders ...string) protocol.ClusterConfig {
  222. var cc protocol.ClusterConfig
  223. for _, folder := range folders {
  224. cc.Folders = append(cc.Folders, protocol.Folder{
  225. ID: folder,
  226. Devices: []protocol.Device{
  227. {
  228. ID: local,
  229. },
  230. {
  231. ID: remote,
  232. },
  233. },
  234. })
  235. }
  236. return cc
  237. }
  238. func localIndexUpdate(m *testModel, folder string, fs []protocol.FileInfo) {
  239. m.fmut.RLock()
  240. fset := m.folderFiles[folder]
  241. m.fmut.RUnlock()
  242. fset.Update(protocol.LocalDeviceID, fs)
  243. seq := fset.Sequence(protocol.LocalDeviceID)
  244. filenames := make([]string, len(fs))
  245. for i, file := range fs {
  246. filenames[i] = file.Name
  247. }
  248. m.evLogger.Log(events.LocalIndexUpdated, map[string]interface{}{
  249. "folder": folder,
  250. "items": len(fs),
  251. "filenames": filenames,
  252. "sequence": seq,
  253. "version": seq, // legacy for sequence
  254. })
  255. }