RavenDb : Force indexes to wait until not stale whilst unit testing

前端 未结 3 505
伪装坚强ぢ
伪装坚强ぢ 2020-12-14 07:36

When unit testing with RavenDb, it is often the case that newly added data is retrieved or otherwise processed. This can lead to \'stale index\' exceptions e.g.

相关标签:
3条回答
  • 2020-12-14 08:31

    If you have a Map/Reduce index, DefaultQueryingConsistency = ConsistencyOptions.QueryYourWrites won't work. You need to use an alternative method.

    In your units tests, call code like this, straight after you've inserted any data, this will force the all indexes to update before you do anything else:

    while (documentStore.DatabaseCommands.GetStatistics().StaleIndexes.Length != 0)
    {
        Thread.Sleep(10);
    }
    

    Update You can of course put it in an extension method if you want to:

    public static class IDocumentSessionExt
    {
        public static void ClearStaleIndexes(this IDocumentSession db)
        {
            while (db.Advanced.DatabaseCommands.GetStatistics().StaleIndexes.Length != 0)
            {
                Thread.Sleep(10);
            }
        }
    }
    

    Then you can say:

    db.ClearStaleIndexes();
    
    0 讨论(0)
  • 2020-12-14 08:34

    Be aware that StaleIndexes also include abondoned and disabled indices - which will never get up to date.

    So to avoid waiting indefinetely use this property instead:

     var staleIndices = store.DatabaseCommands.GetStatistics().CountOfStaleIndexesExcludingDisabledAndAbandoned;
    
    0 讨论(0)
  • 2020-12-14 08:38

    You can actually add a query listener on the DocumentStore to wait for nonstale results. This can be used just for unit tests as it is on the document store and not each operation.

    // Initialise the Store.
    var documentStore = new EmbeddableDocumentStore
                    {
                        RunInMemory = true
                    };
    documentStore.Initialize();
    
    // Force queries to wait for indexes to catch up. Unit Testing only :P
    documentStore.RegisterListener(new NoStaleQueriesListener());
    
    ....
    
    
    #region Nested type: NoStaleQueriesListener
    
    public class NoStaleQueriesListener : IDocumentQueryListener
    {
        #region Implementation of IDocumentQueryListener
    
        public void BeforeQueryExecuted(IDocumentQueryCustomization queryCustomization)
        {
            queryCustomization.WaitForNonStaleResults();
        }
    
        #endregion
    }
    
    #endregion
    

    (Shamelessly stolen from RavenDB how to flush?)

    0 讨论(0)
提交回复
热议问题