How to mock two same mongo collection with different results? - mongodb

I have to mock the two aggregate pipeline methods which point to the same collection.
sample Code below
private void GetMethod()
{
var result1 = databaseContext.GetCollection<SampleCollection>("SampleCollection")
.Aggregate<SampleModel>(aggregateQuery, new AggregateOptions { AllowDiskUse = true }).ToList();
var result2 = databaseContext.GetCollection<SampleCollection>("SampleCollection")
.Aggregate<SampleModel>(aggregateQuery, new AggregateOptions { AllowDiskUse = true }).ToList();
}
Below is the code I try to mock the Collection.
List<SampleModel> models = new List<SampleModel>
{
new SampleModel
{
Quarter = 20141,
Type = "AA",
PaidAmount = 100
},
new SampleModel
{
Quarter = 20141,
Type = "BB",
PaidAmount = 200
}
};
var mockMongoCollection = new Mock<IMongoCollection<SampleCollection>>();
var mockCursor = new Mock<IAsyncCursor<SampleModel>>();
mockCursor.Setup(x => x.Current).Returns(models);
mockCursor.SetupSequence(x => x.MoveNext(It.IsAny<CancellationToken>())).Returns(true).Returns(false);
mockMongoCollection.SetupSequence(x => x.Aggregate(It.IsAny<PipelineDefinition<SampleCollection, SampleModel>>(), It.IsAny<AggregateOptions>(), It.IsAny<CancellationToken>()))
.Returns(mockCursor.Object);
this.mockDbContext.Setup(x => x.GetCollection<SampleCollection>(It.IsAny<string>()))
.Returns(mockMongoCollection.Object);
How to mock and set up the different results for each aggregate? . The mock code I tried only working for the first aggregate query.

The key here is to uniquely identify the two invocations for both the pipelines.
If you are certain which pipeline invocation in your test would execute first, you can make use of the SetupSequence to control the return values. You have already used in your MoveNext method mock setup. It wouldn't matter what the pipeline definitions looks like for both.
If that is not the case, then you would need to write conditions to uniquely identify the invocations.
For example:
mockMongoCollection.SetupSequence(c =>
c.Aggregate(
It.Is<PipelineDefinition<SampleCollection, SampleModel>>(x => x.Stages.Count() == 2),
It.IsAny<AggregateOptions>(),
It.IsAny<CancellationToken>()))
.Returns(mockCursor.Object);
The above example simply demonstrates to identify based on how many stages are defined in a pipeline. Say if there were 2 stages in the first pipeline and the second pipeline had 3 stages, then you can use this to setup your mock.
You can also make use of other properties that you can use to express the condition to determine the invocation correctly and setup correct return value.

Got it worked after initialize the individual cursor for each result.
var mockCursorfirstAggregate = new Mock<IAsyncCursor<SampleModel>>();
mockCursorfirstAggregate.Setup(_ => _.Current).Returns(expectedFirstAggregateResult);
mockCursorfirstAggregate
.SetupSequence(_ => _.MoveNext(It.IsAny<CancellationToken>()))
.Returns(true)
.Returns(false);
var mockCursorsecondAggregate = new Mock<IAsyncCursor<SampleModel>>();
mockCursorsecondAggregate.Setup(_ => _.Current).Returns(expectedSecondAggregateResult);
mockCursorsecondAggregate
.SetupSequence(_ => _.MoveNext(It.IsAny<CancellationToken>()))
.Returns(true)
.Returns(false);
this.mockDbContext.SetupSequence(x => x.GetCollection<SampleCollection>(It.IsAny<string>()).Aggregate(It.IsAny<PipelineDefinition<SampleCollection, SampleModel>>(), It.IsAny<AggregateOptions>(), It.IsAny<CancellationToken>()))
.Returns(mockCursorfirstAggregate.Object)
.Returns(mockCursorsecondAggregate.Object);

Related

nDepend - how to modify "JustMyCode" queries using nDepend API?

My goal is to modify "JustMyCode" queries using nDepend API. I am using code like:
var justMyCodeGroup = prj.CodeQueries.CodeQueriesSet.ChildGroups.Single(x => x.Name.Contains("JustMyCode"));
var originalQuery = justMyCodeGroup.ChildQueries
.Single(x => x.QueryString.Contains("Discard generated Types from JustMyCode"));
var changedQuery = originalQuery.Controller.CreateQuery(originalQuery.IsActive,
query,
originalQuery.
DisplayStatInReport,
originalQuery.DisplayListInReport,
originalQuery.DisplaySelectionViewInReport,
originalQuery.IsCriticalRule);
var justMyCodeGroupWithModifiedQuery = justMyCodeGroup.ReplaceQuery(originalQuery, changedQuery);
prj.CodeQueries.CodeQueriesSet.ReplaceGroup(justMyCodeGroup, justMyCodeGroupWithModifiedQuery);
However, when I run the code above I get ArgumentException with message:
newGroup.Controller is different than this groupOfGroups.Controller
Any help ?
Update 1:
I also tried code:
var justMyCodeGroup = prj.CodeQueries.CodeQueriesSet.ChildGroups.Single(x => x.Name.Contains("JustMyCode"));
var originalQuery = justMyCodeGroup.ChildQueries
.Single(x => x.QueryString.Contains("Discard generated Types from JustMyCode"));
var changedQuery = originalQuery.Controller.CreateQuery(originalQuery.IsActive,
query,
originalQuery.
DisplayStatInReport,
originalQuery.DisplayListInReport,
originalQuery.DisplaySelectionViewInReport,
originalQuery.IsCriticalRule);
var justMyCodeGroupWithModifiedQuery = justMyCodeGroup.ReplaceQuery(originalQuery, changedQuery);
var newQueries = new List<IQuery>();
foreach (var q in justMyCodeGroup.ChildQueries)
{
if (q.QueryString.Contains("Discard generated Types from JustMyCode"))
{
continue;
}
newQueries.Add(prj.CodeQueries.CodeQueriesSet.Controller.CreateQuery(q.IsActive, q.QueryString,
q.DisplayStatInReport, q.DisplayListInReport, q.DisplaySelectionViewInReport, q.IsCriticalRule));
}
newQueries.Add(prj.CodeQueries.CodeQueriesSet.Controller.CreateQuery(originalQuery.IsActive, query, originalQuery.DisplayStatInReport, originalQuery.DisplayListInReport, originalQuery.DisplaySelectionViewInReport, originalQuery.IsCriticalRule));
var newGroup = prj.CodeQueries.CodeQueriesSet.Controller.CreateGroup(justMyCodeGroup.Name,
justMyCodeGroup.IsActive, justMyCodeGroup.ShownInReport, newQueries, new List<IGroup>());
prj.CodeQueries.CodeQueriesSet.RemoveGroup(justMyCodeGroup);
prj.CodeQueries.CodeQueriesSet.AddGroup(newGroup);
Right now, RemoveGroup throws exception:
this group of groups doesn't contain groupToRemove.
Update 2:
And I also wonder, why does this code return false ?
var justMyCodeGroup = prj.CodeQueries.CodeQueriesSet.ChildGroups.Single(x => x.Name.Contains("JustMyCode"));
prj.CodeQueries.CodeQueriesSet.ContainsGroup(justMyCodeGroup)
Refer to the PowerTools source file:
$NDependInstallDir$\NDepend.PowerTools.SourceCode\CQL2CQLinq\CQL2CQLinqPowerTool.cs
This PowerTools convert code queries written with old CQL syntax into code queries written with new CQLinq syntax, hence it loads the queries set from a project, update CQL queries, and then save the new queries set in the project.
The queriesController is gathered this way...
var queriesSet = project.CodeQueries.CodeQueriesSet;
var queriesController = queriesSet.Controller;
... and then used this way to modify the queries set:
queriesController.DoUpdateQueryObject(query, newQuery);

declare variable to store linq entity for conditional statements

I am trying to look up record using if I have the key then use Find if not use Where
private ApplicationDbContext db = new ApplicationDbContext();
public bool DeactivatePrice(int priceId = 0, string sponsorUserName = "")
{
var prices = db.BeveragePrices;
// if we have an id then find
if (priceId != 0)
{
prices = prices.Find(priceId);
}
else
{
prices = prices.Where(b => b.UserCreated == sponsorUserName);
}
if (prices != null)
{
// do something
}
return true;
I get the following error for
prices = prices.Find(priceId);
Cannot convert app.Model.BeveragePrices from system.data.entity.dbset
I am copying the pattern from this answer but something must be different.
Seems you forgot to put a predicate inside the Find function call. Also you need to do ToList on the collection. The second option is a lot more efficient. The first one gets the whole collection before selection.
Another note commented by #Alla is that the find returns a single element. So I assume another declaration had been made for 'price' in the first option I state down here.
price = prices.ToList.Find(b => b.PriceId == priceId);
Or
prices = prices.Select(b => b.PriceId == priceId);
I assume the field name is PriceId.

How to obtain a subset of records within a context using EntityFramework?

A newbie question. I am using EntityFramework 4.0. The backend database has a function that will return a subset of records based on time.
Example of working code is:
var query = from rx in context.GetRxByDate(tencounter,groupid)
select rx;
var result = context.CreateDetachedCopy(query.ToList());
return result;
I need to verify that a record does not exist in the database before inserting a new record. Before performing the "Any" filter, I would like to populate the context.Rxes with a subset of the larger backend database using the above "GetRxByDate()" function.
I do not know how to populate "Rxes" before performing any further filtering since Rxes is defined as
IQueryable<Rx> Rxes
and does not allow "Rxes =.. ". Here is what I have so far:
using (var context = new EnityFramework())
{
if (!context.Rxes.Any(c => c.Cform == rx.Cform ))
{
// Insert new record
Rx r = new Rx();
r.Trx = realtime;
context.Add(r);
context.SaveChanges();
}
}
I am fully prepared to kick myself since I am sure the answer is simple.
All help is appreciated. Thanks.
Edit:
If I do it this way, "Any" seems to return the opposite results of what is expected:
var g = context.GetRxByDate(tencounter, groupid).ToList();
if( g.Any(c => c.Cform == rx.Cform ) {....}

Entity Framework check against a local list

I have a local list of values that I need to have entity framework check against the database and return them.
If the list was already in the database, the following would work:
var list = /* some ef query */;
var myList = context.Logs.Where(l => list.Any(li => l.LogNumber == li.LogNumber));
But if the list is local, it would throw an error:
var list = new List<Log>();
var myList = context.Logs.Where(l => list.Any(li => l.LogNumber == li.LogNumber));
Exception: Unable to process the type 'Data.Log[]', because it has no known mapping to the value layer.
So how can I match a local list against a database list using EF?
I got a different error than you with the code sample, but I believe it's the same idea. EF doesn't know how to translate List<Log> into a SQL store expression. It works when you're still in a query because it hasn't been serialized yet.
I realize this is less than ideal, but I was able to make this query work by extracting the scalar values of LogNumber and then using that in the query.
var list = new List<Log>();
list.Add(new Log()
{
LogNumber = 1
});
var numbers = list.Select(l => l.LogNumber);
var myList = m.Logs.Where(l => numbers.Contains(l.LogNumber));

MongoDB - combining multiple Numeric Range queries (C# driver)

*Mongo Newbie here
I have a document containing several hundred numeric fields which I need to query in combination.
var collection = _myDB.GetCollection<MyDocument>("collection");
IMongoQuery mongoQuery; // = Query.GT("field", value1).LT(value2);
foreach (MyObject queryObj in Queries)
{
// I have several hundred fields such as Height, that are in queryObj
// how do I build a "boolean" query in C#
mongoQuery = Query.GTE("Height", Convert.ToInt16(queryObj.Height * lowerbound));
}
I have several hundred fields such as Height (e.g. Width, Area, Perimeter etc.), that are in queryObj how do I build a "boolean" query in C# that combines range queries for each field in conjunction.
I have tried to use the example Query.GT("field", value1).LT(value2);, however the compiler does not accept the LT(Value) construct. In any event I need to be able to build a complex boolean query by looping through each of the numeric field values.
Thanks for helping a newbie out.
EDIT 3:
Ok, it looks like you already have code in place to build the complicated query. In that case, you just needed to fix the compiler issue. Am assuming you want to do the following (x > 20 && x < 40) && (y > 30 && y < 50) ...
var collection = _myDB.GetCollection<MyDocument>("collection");
var queries = new List<IMongoQuery>();
foreach (MyObject queryObj in Queries)
{
//I have several hundred fields such as Height, that are in queryObj
//how do I build a "boolean" query in C#
var lowerBoundQuery = Query.GTE("Height", Convert.ToInt16(queryObj.Height * lowerbound));
var upperBoundQuery = Query.LTE("Height", Convert.ToInt16(queryObj.Height * upperbound));
var query = Query.And(lowerBoundQuery, upperBoundQuery);
queries.Add(query);
}
var finalQuery = Query.And(queries);
/*
if you want to instead do an OR,
var finalQuery = Query.Or(queries);
*/
Original Answer.
var list = _myDb.GetCollection<MyDoc>("CollectionName")
.AsQueryable<MyDoc>()
.Where(x =>
x.Height > 20 &&
x.Height < 40)
.ToList();
I have tried to use the example Query.GT("field", value1).LT(value2);,
however the compiler does not accept the LT(Value) construct.
You can query MongoDB using linq, if you are using the official C# driver. That ought to solve the compiler issue I think.
The more interesting question I have in mind is, how are you going to construct that complicated boolean query?
One option is to dynamically build an Expression and then pass that to the Where
My colleague is using the following code for something similar...
public static IQueryable<T> Where<T>(this IQueryable<T> query,
string column, object value, WhereOperation operation)
{
if (string.IsNullOrEmpty(column))
return query;
ParameterExpression parameter = Expression.Parameter(query.ElementType, "p");
MemberExpression memberAccess = null;
foreach (var property in column.Split('.'))
memberAccess = MemberExpression.Property
(memberAccess ?? (parameter as Expression), property);
//change param value type
//necessary to getting bool from string
ConstantExpression filter = Expression.Constant
(
Convert.ChangeType(value, memberAccess.Type)
);
//switch operation
Expression condition = null;
LambdaExpression lambda = null;
switch (operation)
{
//equal ==
case WhereOperation.Equal:
condition = Expression.Equal(memberAccess, filter);
lambda = Expression.Lambda(condition, parameter);
break;
//not equal !=
case WhereOperation.NotEqual:
condition = Expression.NotEqual(memberAccess, filter);
lambda = Expression.Lambda(condition, parameter);
break;
//string.Contains()
case WhereOperation.Contains:
condition = Expression.Call(memberAccess,
typeof(string).GetMethod("Contains"),
Expression.Constant(value));
lambda = Expression.Lambda(condition, parameter);
break;
}
MethodCallExpression result = Expression.Call(
typeof(Queryable), "Where",
new[] { query.ElementType },
query.Expression,
lambda);
return query.Provider.CreateQuery<T>(result);
}
public enum WhereOperation
{
Equal,
NotEqual,
Contains
}
Currently it only supports == && !=, but it shouldn't be that difficult to implement >= or <= ...
You could get some hints from the Expression class: http://msdn.microsoft.com/en-us/library/system.linq.expressions.expression.aspx
EDIT:
var props = ["Height", "Weight", "Age"];
var query = _myDb.GetCollection<MyDoc>("CName").AsQueryable<MyDoc>();
foreach (var prop in props)
{
query = query.Where(prop, GetLowerLimit(queryObj, prop), WhereOperation.Between, GetUpperLimit(queryObj, prop));
}
// the above query when iterated over, will result in a where clause that joins each individual `prop\condition` with an `AND`.
// The code above will not compile. The `Where` function I wrote doesnt accept 4 parameters. You will need to implement the logic for that yourself. Though it ought to be straight forward I think...
EDIT 2:
If you don't want to use linq, you can still use Mongo Query. You will just need to craft your queries using the Query.And() and Query.Or().
// I think this might be deprecated. Please refer the release notes for the C# driver version 1.5.0
Query.And(Query.GTE("Salary", new BsonDouble(20)), Query.LTE("Salary", new BsonDouble(40)), Query.GTE("Height", new BsonDouble(20)), Query.LTE("Height", new BsonDouble(40)))
// strongly typed version
new QueryBuilder<Employee>().And(Query<Employee>.GTE(x => x.Salary, 40), Query<Employee>.LTE(x => x.Salary, 60), Query<Employee>.GTE(x => x.HourlyRateToClients, 40), Query<Employee>.LTE(x => x.HourlyRateToClients, 60))