Skip to content

Instantly share code, notes, and snippets.

@RobertTheGrey
Created July 3, 2012 10:01
Show Gist options
  • Save RobertTheGrey/3038836 to your computer and use it in GitHub Desktop.
Save RobertTheGrey/3038836 to your computer and use it in GitHub Desktop.
Query Raven by Index in a unit test
public static class DocumentStoreExtensions
{
public static void SaveSessionAction(this IDocumentStore documentStore, Action<IDocumentSession> action)
{
using (IDocumentSession session = documentStore.OpenSession())
{
action(session);
session.SaveChanges();
documentStore.WaitForStaleIndexes();
}
}
public static void WaitForStaleIndexes(this IDocumentStore documentStore)
{
while (documentStore.DatabaseCommands.GetStatistics().StaleIndexes.Length != 0)
{
Thread.Sleep(50);
}
}
}
public class TagsCountByStory : AbstractIndexCreationTask<Story, TagsCountByStory.Result>
{
public TagsCountByStory()
{
Map = stories => from story in stories
from tag in story.Tags
select new
{
TagName = tag,
Count = 1
};
Reduce = tagMaps => from tagMap in tagMaps
group tagMap by tagMap.TagName
into tagGroup
select new
{
TagName = tagGroup.Key,
Count = tagGroup.Sum(x => x.StoryCount)
};
}
public override string IndexName
{
get { return "Stories/StoryCountByTag"; }
}
public class Result
{
public string TagName { get; set; }
public int StoryCount { get; set; }
}
}
public WhenLoadingTheTagsPage()
{
_documentStore = new EmbeddableDocumentStore
{
RunInMemory = true,
Conventions = new DocumentConvention
{
DefaultQueryingConsistency = ConsistencyOptions.QueryYourWrites
}
};
_documentStore.Initialize();
_documentStore.RegisterListener(new PreventStaleQueries());
IndexCreation.CreateIndexes(typeof(IndexMarker).Assembly, _documentStore);
_config = new ConfigurationStore(new TypeMapFactory(), MapperRegistry.AllMappers());
_config.AddProfile<StoryViewModelProfile>();
}
[Test]
public void ShouldReturnAListOfTagsWithStoryCount()
{
Story normalStory = SampleData.GetSampleStory();
Story legacyStory = SampleData.GetSampleLegacyStory();
_documentStore.SaveSessionAction(session =>
{
session.Store(normalStory); //Contains 1 Tag
session.Store(legacyStory); //Contains 1 Tag
});
using (var session = _documentStore.OpenSession())
{
var tagsByStoryCount = session
.Query<TagsCountByStory.Result, TagsCountByStory>()
.OrderBy(x => x.TagName);
Console.WriteLine(tagsByStoryCount.Count()); //Output is zero tags found
tagsByStoryCount.ShouldNotBeEmpty(); // FAIL: This is empty for some reason
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment