Multiple calls to a Rhino mocked method return different results - rhino-mocks

If I want to mock a class that returns a string that is used to determine whether while loop should continue (imagine read while string != null), how can I set the expectation. I have tried the following:
provider.Reader.Expect(r => r.ReadLine()).Return("1,10,20");
provider.Reader.Expect(r => r.ReadLine()).Return(null);
but when it is called twice in the same method, it returns the first string on both occasions, whereas I want it to return the second value (null) if called a second time.

I think you can just stick the repeat on the end of the syntax you're currently using.
provider.Reader.Expect(r => r.ReadLine()).Return("1,10,20").Repeat.Once();
provider.Reader.Expect(r => r.ReadLine()).Return(null).Repeat.Once();
or
provider.Reader.Expect(r => r.ReadLine()).Return("1,10,20").Repeat.Once();
provider.Reader.Expect(r => r.ReadLine()).Return(null);
if you have any calls beyond 2nd call that you want to use second expectation.

I'm not familiar with the syntax you're using. I would write this as:
r.ReadLine();
LastCall.Return("1,10,20").Repeat.Once();
r.ReadLine();
LastCall.Return(null).Repeat.Once();
To ensure that you're specifying the number of times that things are to be repeated. (Don't have Visual Studio to hand, syntax may not be exact.)

Related

How to Convert foor loop to NHibernate Futures for performance

NHibernate Version: 3.4.0.4000
I'm currently working on optimizing our code so that we can reduce the number of round trips to the database and am looking at a for loop that is one of the culprits. I'm having a hard time figuring out how to batch all of these iterations into a future that gets executed once when sent to SQL Server. Essentially each iteration of the loop causes 2 queries to hit the database!
foreach (var choice in lineItem.LineItemChoices)
{
choice.OptionVersion = _session.Query<OptionVersion>().Where(x => x.Option.Id == choice.OptionId).OrderByDescending(x => x.OptionVersionNumber).FirstOrDefault();
choice.ChoiceVersion = _session.Query<ChoiceVersion>().OrderByDescending(x => x.ChoiceVersionIdentity.ChoiceVersionNumber).Where(x => x.Choice.Id == choice.ChoiceId).FirstOrDefault();
}
One option is to extract OptionId and ChoiceId from all the LineItemChoices into two lists in local memory. Then issue just two queries, one for options and one for choices, giving these lists in .Where(x => optionIds.Contains(x.Option.Id)). This corresponds to SQL IN operator. This requires some postprocessing. You will get two result lists (transform to dictionary or lookup if you expect many results), that you need to process to populate the choice objects. This postprocessing is local and tends to be very cheap compared to database roundtrips. This option can be a bit tricky if the existing FirstOrDefault part is absolutely necessary. Do you expect there to be more than result for a single optionId? If not, this code could instead have used SingleOrDefault, which could just be dropped if converting to use IN-queries.
The other option is to use futures (https://nhibernate.info/doc/nhibernate-reference/performance.html#performance-future). For Linq it means to use ToFuture or ToFutureValue at the end, which also conflicts with FirstOrDefault I believe. The important thing is that you need to loop over all line item choices to initialize ALL queries BEFORE you access the value of any of them. So this is likely to also result in some postprocessing, where you would first store the future values in some list, and then in a second loop access the real value from each query to populate the line item choice.
If you to expect that the queries can yield more than one result (before applying FirstOrDefault), I think you can just use Take(1) instead, as that will still return an IQueryable where you can apply the future method.
The first option is probably the most efficient, since it will just be two queries and allow the database engine to make just one pass over the tables.
Keep the limit on the maximum number of parameters that can be given in an SQL query in mind. If there can be thousands of line item choices, you may need to split them in batches and query for at most 2000 identifiers per round trip.
Adding on the Oskar answer, NHibernate Futures was implement in NHibernate 2.1. It is available on method Future for collections and FutureValue for single values.
In your case, you could separate the IDs of the list in memory ...
var optionIds = lineItem.LineItemChoices.Select(x => x.OptionId);
var choiceIds = lineItem.LineItemChoices.Select(x => x.ChoiceId);
... and execute two queries using Future<T> to get two lits in one hit over the database.
var optionVersions = _session.Query<OptionVersion>()
.Where(x => optionIds.Contains(x.Option.Id))
.OrderByDescending(x => x.OptionVersionNumber)
.Future<OptionVersion>();
var choiceVersions = _session.Query<ChoiceVersion>()
.Where(x => choiceIds.Contains(x.Choice.Id))
.OrderByDescending(x => x.ChoiceVersionIdentity.ChoiceVersionNumber)
.Future<ChoiceVersion>();
After with all you need in memory, you could loop on the original collection you have and search in memory the data to fill up the choice object.
foreach (var choice in lineItem.LineItemChoices)
{
choice.OptionVersion = optionVersions.OrderByDescending(x => x.OptionVersionNumber).FirstOrDefault(x => x.Option.Id == choice.OptionId);
choice.ChoiceVersion = choiceVersions.OrderByDescending(x => x.ChoiceVersionIdentity.ChoiceVersionNumber).FirstOrDefault(x => x.Choice.Id == choice.ChoiceId);
}

How to Set Postman Test Equal to This or That

I am writing an API test in Postman, and I would like it to succeed if a Number is returned or the string "NA".
Based on my current understanding one condition can be tested at a time, like:
pm.test('Qty returned is number', () => {
pm.expect(typeof parseInt(pm.response.json().qty)).to.be.not.equal('NaN');
});
Writing as two separate tests, one will pass and one will fail.
How can I code this exception into a single test?
Worked for my case, wanted the test to pass if one of two values is returned:
.to.be.oneOf(["value1","value2"]);
answer from jaikl

Where clause using LIKE condition in MVC4 lambda

I want to show results where w.DrawDate contains (LIKE %year%) the year.
return View(db.Euro.Select(p => p).Where(w => w.DrawDate == year).ToList());
As seen in Like condition in MVC4 using lambda, i should use the Contains() method, but it isn't available.
So, how can i make w.DrawDate == year into w.DrawDate LIKE %year%?
You already have the answer:
View(db.Euro.Where(w => w.DrawDate.Contains(year)).ToList());
And you're probably just missing a namespace

How do I get the results of the Plucky Query inside my controller?

I'm missing something simple - I do not want to access the results of this query in a view.
Here is the query:
#adm = Admin.where({:id => {"$ne" => params[:id].to_s},:email => params[:email]})
And of course when you inspect you get:
#adm is #<MongoMapper::Plugins::Querying::DecoratedPluckyQuery:0x007fb4be99acd0>
I understand (from asking the MM guys) why this is the case - they wished to delay the results of the actual query as long as possible, and only get a representation of the query object until we render (in a view!).
But what I'm trying to ascertain in my code is IF one of my params matches or doesn't match the result of my query in the controller so I can either return an error message or proceed.
Normally in a view I'm going to do:
#adm.id
To get the BSON out of this. When you try this on the Decorated Query of course it fails:
NoMethodError (undefined method `id' for #<MongoMapper::Plugins::Querying::DecoratedPluckyQuery:0x007fb4b9e9f118>)
This is because it's not actually a Ruby Object yet, it's still the query proxy.
Now I'm fundamentally missing something because I never read a "getting started with Ruby" guide - I just smashed my way in here and learned through brute-force. So, what method do I call to get the results of the Plucky Query?
The field #adm is set to a query as you've seen. So, to access the results, you'll need to trigger execution of the query. There are a variety of activation methods you can call, including all, first, and last. There's a little documentation here.
In this case, you could do something like:
adm_query = Admin.where({:id => {"$ne" => params[:id].to_s},:email => params[:email]})
#adm_user = adm_query.first
That would return you the first user and after checking for nil
if #adm_user.nil?
# do something if no results were found
end
You could also limit the query results:
adm_query = Admin.where( ... your query ...).limit(1)

Querying attributes where value is not yet set

Any of you guys know how to query rally for a set of things where an string attribute value is currently not yet set?
I can’t query for the value equal to an empty string. That doesn’t parse. And I can’t use “null” either. Or rather, I can try “null” and it parses fine but it doesn’t result in finding anything.
query = #rally_api.find(:defect, :fetch =>true,
:project_scope_up => false, :project_scope_down => false,
:workspace => #workspace,
:project => #project) { equals :integration_i_d, "" }
This was followed up by telling the me to substitute "" with nil which didn't work. Null was tried to no success as well. I've tried "null" and null and "". None of them work.
I'm not familiar with our Ruby REST toolkit but directly hitting our WSAPI, you would say (<Field> = null). Notice that there are no quotes around "null".
Also, I'm wondering if the use of contains in your example above is what you wanted. You might want =.
try: { equal :integration_i_d, '""' }
Also, if rally_rest_api seems slow - we're working on something faster here:
http://developer.rallydev.com/help/ruby-rally-api