testutils_test.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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(t testing.TB) (*testModel, *fakeConnection, config.FolderConfiguration) {
  86. t.Helper()
  87. w, fcfg := tmpDefaultWrapper()
  88. m, fc := setupModelWithConnectionFromWrapper(t, w)
  89. return m, fc, fcfg
  90. }
  91. func setupModelWithConnectionFromWrapper(t testing.TB, w config.Wrapper) (*testModel, *fakeConnection) {
  92. t.Helper()
  93. m := setupModel(t, w)
  94. fc := addFakeConn(m, device1)
  95. fc.folder = "default"
  96. _ = m.ScanFolder("default")
  97. return m, fc
  98. }
  99. func setupModel(t testing.TB, w config.Wrapper) *testModel {
  100. t.Helper()
  101. m := newModel(t, w, myID, "syncthing", "dev", nil)
  102. m.ServeBackground()
  103. <-m.started
  104. m.ScanFolders()
  105. return m
  106. }
  107. type testModel struct {
  108. *model
  109. cancel context.CancelFunc
  110. evCancel context.CancelFunc
  111. stopped chan struct{}
  112. }
  113. func newModel(t testing.TB, cfg config.Wrapper, id protocol.DeviceID, clientName, clientVersion string, protectedFiles []string) *testModel {
  114. t.Helper()
  115. evLogger := events.NewLogger()
  116. ldb, err := db.NewLowlevel(backend.OpenMemory(), evLogger)
  117. if err != nil {
  118. t.Fatal(err)
  119. }
  120. m := NewModel(cfg, id, clientName, clientVersion, ldb, protectedFiles, evLogger).(*model)
  121. ctx, cancel := context.WithCancel(context.Background())
  122. go evLogger.Serve(ctx)
  123. return &testModel{
  124. model: m,
  125. evCancel: cancel,
  126. stopped: make(chan struct{}),
  127. }
  128. }
  129. func (m *testModel) ServeBackground() {
  130. ctx, cancel := context.WithCancel(context.Background())
  131. m.cancel = cancel
  132. go func() {
  133. m.model.Serve(ctx)
  134. close(m.stopped)
  135. }()
  136. <-m.started
  137. }
  138. func cleanupModel(m *testModel) {
  139. if m.cancel != nil {
  140. m.cancel()
  141. <-m.stopped
  142. }
  143. m.evCancel()
  144. m.db.Close()
  145. os.Remove(m.cfg.ConfigPath())
  146. }
  147. func cleanupModelAndRemoveDir(m *testModel, dir string) {
  148. cleanupModel(m)
  149. os.RemoveAll(dir)
  150. }
  151. func createTmpDir() string {
  152. tmpDir, err := ioutil.TempDir("", "syncthing_testFolder-")
  153. if err != nil {
  154. panic("Failed to create temporary testing dir")
  155. }
  156. return tmpDir
  157. }
  158. type alwaysChangedKey struct {
  159. fs fs.Filesystem
  160. name string
  161. }
  162. // alwaysChanges is an ignore.ChangeDetector that always returns true on Changed()
  163. type alwaysChanged struct {
  164. seen map[alwaysChangedKey]struct{}
  165. }
  166. func newAlwaysChanged() *alwaysChanged {
  167. return &alwaysChanged{
  168. seen: make(map[alwaysChangedKey]struct{}),
  169. }
  170. }
  171. func (c *alwaysChanged) Remember(fs fs.Filesystem, name string, _ time.Time) {
  172. c.seen[alwaysChangedKey{fs, name}] = struct{}{}
  173. }
  174. func (c *alwaysChanged) Reset() {
  175. c.seen = make(map[alwaysChangedKey]struct{})
  176. }
  177. func (c *alwaysChanged) Seen(fs fs.Filesystem, name string) bool {
  178. _, ok := c.seen[alwaysChangedKey{fs, name}]
  179. return ok
  180. }
  181. func (c *alwaysChanged) Changed() bool {
  182. return true
  183. }
  184. func localSize(t *testing.T, m Model, folder string) db.Counts {
  185. t.Helper()
  186. snap := dbSnapshot(t, m, folder)
  187. defer snap.Release()
  188. return snap.LocalSize()
  189. }
  190. func globalSize(t *testing.T, m Model, folder string) db.Counts {
  191. t.Helper()
  192. snap := dbSnapshot(t, m, folder)
  193. defer snap.Release()
  194. return snap.GlobalSize()
  195. }
  196. func receiveOnlyChangedSize(t *testing.T, m Model, folder string) db.Counts {
  197. t.Helper()
  198. snap := dbSnapshot(t, m, folder)
  199. defer snap.Release()
  200. return snap.ReceiveOnlyChangedSize()
  201. }
  202. func needSize(t *testing.T, m Model, folder string) db.Counts {
  203. t.Helper()
  204. snap := dbSnapshot(t, m, folder)
  205. defer snap.Release()
  206. return snap.NeedSize(protocol.LocalDeviceID)
  207. }
  208. func dbSnapshot(t *testing.T, m Model, folder string) *db.Snapshot {
  209. t.Helper()
  210. snap, err := m.DBSnapshot(folder)
  211. if err != nil {
  212. t.Fatal(err)
  213. }
  214. return snap
  215. }
  216. // Reach in and update the ignore matcher to one that always does
  217. // reloads when asked to, instead of checking file mtimes. This is
  218. // because we will be changing the files on disk often enough that the
  219. // mtimes will be unreliable to determine change status.
  220. func folderIgnoresAlwaysReload(t testing.TB, m *testModel, fcfg config.FolderConfiguration) {
  221. t.Helper()
  222. m.removeFolder(fcfg)
  223. fset := newFileSet(t, fcfg.ID, fcfg.Filesystem(), m.db)
  224. ignores := ignore.New(fcfg.Filesystem(), ignore.WithCache(true), ignore.WithChangeDetector(newAlwaysChanged()))
  225. m.fmut.Lock()
  226. m.addAndStartFolderLockedWithIgnores(fcfg, fset, ignores)
  227. m.fmut.Unlock()
  228. }
  229. func basicClusterConfig(local, remote protocol.DeviceID, folders ...string) protocol.ClusterConfig {
  230. var cc protocol.ClusterConfig
  231. for _, folder := range folders {
  232. cc.Folders = append(cc.Folders, protocol.Folder{
  233. ID: folder,
  234. Devices: []protocol.Device{
  235. {
  236. ID: local,
  237. },
  238. {
  239. ID: remote,
  240. },
  241. },
  242. })
  243. }
  244. return cc
  245. }
  246. func localIndexUpdate(m *testModel, folder string, fs []protocol.FileInfo) {
  247. m.fmut.RLock()
  248. fset := m.folderFiles[folder]
  249. m.fmut.RUnlock()
  250. fset.Update(protocol.LocalDeviceID, fs)
  251. seq := fset.Sequence(protocol.LocalDeviceID)
  252. filenames := make([]string, len(fs))
  253. for i, file := range fs {
  254. filenames[i] = file.Name
  255. }
  256. m.evLogger.Log(events.LocalIndexUpdated, map[string]interface{}{
  257. "folder": folder,
  258. "items": len(fs),
  259. "filenames": filenames,
  260. "sequence": seq,
  261. "version": seq, // legacy for sequence
  262. })
  263. }
  264. func newFileSet(t testing.TB, folder string, fs fs.Filesystem, ldb *db.Lowlevel) *db.FileSet {
  265. t.Helper()
  266. fset, err := db.NewFileSet(folder, fs, ldb)
  267. if err != nil {
  268. t.Fatal(err)
  269. }
  270. return fset
  271. }