MockBookmarkDataSource.cs
 1  // Copyright (c) Microsoft Corporation
 2  // The Microsoft Corporation licenses this file to you under the MIT license.
 3  // See the LICENSE file in the project root for more information.
 4  
 5  using System;
 6  using System.Threading;
 7  using Microsoft.CmdPal.Ext.Bookmarks.Persistence;
 8  
 9  namespace Microsoft.CmdPal.Ext.Bookmarks.UnitTests;
10  
11  internal sealed class MockBookmarkDataSource : IBookmarkDataSource
12  {
13      private string _jsonData;
14      private int _saveCount;
15  
16      public MockBookmarkDataSource(string initialJsonData = "[]")
17      {
18          _jsonData = initialJsonData;
19      }
20  
21      public string GetBookmarkData()
22      {
23          return _jsonData;
24      }
25  
26      public void SaveBookmarkData(string jsonData)
27      {
28          _jsonData = jsonData;
29          Interlocked.Increment(ref _saveCount);
30      }
31  
32      public int SaveCount => Volatile.Read(ref _saveCount);
33  
34      // Waits until at least expectedMinSaves have occurred or the timeout elapses.
35      // Returns true if the condition was met, false on timeout.
36      public bool WaitForSave(int expectedMinSaves = 1, int timeoutMs = 2000)
37      {
38          var start = Environment.TickCount;
39          while (Volatile.Read(ref _saveCount) < expectedMinSaves)
40          {
41              if (Environment.TickCount - start > timeoutMs)
42              {
43                  return false;
44              }
45  
46              Thread.Sleep(50);
47          }
48  
49          return true;
50      }
51  }