How to use the AAA syntax to do an AssertWasCalled but ignore arguments - rhino-mocks

I'm using the new AAA syntax and wanted to know the syntax to do the below and have the mock ignore the arguments:
mockAccount.AssertWasCalled(account => account.SetPassword("dsfdslkj"));
I think the below is how I would do this with the record/ replay model but I wanted to see if this could be done with AAA using 3.6:
mockAccount.Expect(account => account.SetPassword("sdfdsf")).IgnoreArguments();
mockAccount.VerifyAllExpectations();

To ignore the arguments, use Arg<string>.Is.Anything:
mockAccount.AssertWasCalled(acc => acc.SetPassword(Arg<string>.Is.Anything));

Found it with the obvious google search - hope someone else finds this of value
mockAccount.AssertWasNotCalled(x => x.SetPassword(""), y => y.IgnoreArguments());

Related

.NET Core - EF - trying to match/replace strings with digits, causes System.InvalidOperationException

I have to match records in SQL around a zip code with a min/max range
the challenge is that the data qualities are bad, some zipcodes are not numbers only
so I try to match "good zip codes" either by discarding bad ones or even keeping only digits
I dont know how to use Regex.Replace(..., #"[^\d]", "") instead of Regex.Match(..., #"\d") to fit in the query bellow
I get an error with the code bellow at runtime
I tried
Regex.IsMatch
SqlFunctions.IsNumeric
they all cause errors at runtime, here is the code :
var data = context.Leads.AsQueryable();
data = data.Include(p => p.Company).Include(p => p.Contact);
data = data.Where(p => Regex.IsMatch(p.Company.ZipCode, #"\d"));
data = data.Where(p => Convert.ToInt32(p.Company.ZipCode) >= range.Min);
data = data.Where(p => Convert.ToInt32(p.Company.ZipCode) <= range.Max);
here is the error :
System.InvalidOperationException: The LINQ expression 'DbSet<Lead>
.Join(
outer: DbSet<Company>,
inner: l => EF.Property<Nullable<int>>(l, "CompanyId"),
outerKeySelector: c => EF.Property<Nullable<int>>(c, "Id"),
innerKeySelector: (o, i) => new TransparentIdentifier<Lead, Company>(
Outer = o,
Inner = i
))
.Where(l => !(Regex.IsMatch(
input: l.Inner.ZipCode,
pattern: "\d")))' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync().
I am not sure how to solve this. I really don't see how AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync() could help here
what do I do wrong ?
thanks for your help
Wnen you use querable list, Ef Core 5 is always trying to translate query to SQl, so you have to use code that SQL server could understand. If you want to use C# function you will have to download data to Server using ToList() or ToArray() at first and after this you can use any c# functions using downloaded data.
You can try something like this:
var data = context.Leads
.Include(p => p.Company)
.Include(p => p.Contact)
.Where(p =>
p.Company.Zipcode.All(char.IsDigit)
&& (Convert.ToInt32(p.Company.ZipCode) >= range.Min) //or >=1
&& ( Convert.ToInt32(p.Company.ZipCode) <= range.Max) ) // or <=99999
.ToArray();
I tried everything imaginable
all sorts of linq/ef trickeries, I even tried to define a DBFunction that was never found
once I had a running stored procedure written dirrectly in SQL, I ended up with a list, not with an IQueryable, so I was back to #1
finaly, I just created a new field in my table :
ZipCodeNum
which holds a filtered , converted version of the zipcode string

Cab Dafny use an imported ADT in a match command

Hi I am running into time out problems and am trying to decompose my file into different modules on the hope that a verified module will not have to be reverified, in VS code, when working on a module that imports it.
If any one knows if this is a reasonable way to avoid time out problems I would like to hear.
But the more basic problem I found is that once I import an ADT I can make use of in in if statements but not in match statements. See code below for an example. Any ideas on what I am doing wrong?
module inner {
datatype Twee = Node(value : int, left : Twee, right : Twee) | Leaf
function rot(t:Twee) :Twee
{
match t
case Leaf => t
case Node(v,l,r) => Node(v,r,l)
}
}
module outer {
import TL = inner
function workingIf(t:TL.Twee) :TL.Twee
{ if (t == TL.Leaf) then TL.Leaf else t }
function failingMatch(t:TL.Twee) :TL.Twee
{
match t
case TL.Leaf => t // error "darrow expected"
case TL.Node(v,l,r) => TL.Node(v,r,l)
}
}
Sorry for asking the question - the following worked.
function failingMatch(t:TL.Twee) :TL.Twee
{
match t
case Leaf => t
case Node(v,l,r) => TL.Node(v,r,l)
}
Well that worked but the following failed
function rotateLeft(t:TL.Twee) :TL.Twee
{
match t
case Leaf => t
case Node(v,Leaf,r) => TL.Node(v,TL.Leaf,r)
case Node(v,Node(vl,ll,rl),r) => TL.Node(vl,ll,TL.Node(v,rl,r))
}
The answer to the first question was given by James Wilcox and can be found in What are the relationships among imports, includes, and verification in Dafny?
but for convienience I repeat below:
"import has no direct influence on whether the imported module is verified or not. Modules in other files will not be verified unless their file is listed on the command line. Modules in the current file are always verified (whether or not they are imported by anyone)."
The main question I have raised in https://github.com/dafny-lang/dafny/issues/870
Many thanks to everyone - teaching how to use Dafny with out stack overflow would be so much harder.
Somewhat oddly, the constructor names that follow each case keyword are expected to be unqualified. They are looked up in the type of the expression that follows the match. It's quirky that qualified names are not allowed, and this is likely something that will be corrected in the future (I thought there was a Dafny issue on github about this, but I can't find it).

Why am I getting “Too many positionals passed…” in this call to HTTP::Request.new?

I tried six or so variations on this code and excepting hardcoded Strs like GET => … I always got this error. Why? How can I fix it and understand it? Is it a bug in the HTTP::Request code?
Code
#!/usr/bin/env perl6
use HTTP::UserAgent; # Installed today with panda, for HTTP::Request.
HTTP::Request.new( GET => "/this/is/fine" ).WHICH.say;
# First, check that yes, they are there.
say %*ENV<REQUEST_METHOD>, " ", %*ENV<REQUEST_URI>;
# This and single value or slice combination always errors-
HTTP::Request.new( %*ENV<REQUEST_METHOD>, %*ENV<REQUEST_URI> );
Output with invariable error
$ env REQUEST_METHOD=GET REQUEST_URI=/ SOQ.p6
HTTP::Request|140331166709152
GET /
Too many positionals passed; expected 1 argument but got 3
in method new at lib/HTTP/Request.pm6:13
in block <unit> at ./SOQ.p6:11
HTTP::Request is from this package — https://github.com/sergot/http-useragent/ — Thank you!
Try
HTTP::Request.new(|{ %*ENV<REQUEST_METHOD> => %*ENV<REQUEST_URI> });
instead of the more obvious
HTTP::Request.new( %*ENV<REQUEST_METHOD> => %*ENV<REQUEST_URI> );
If the left-hand side of => isn't a literal, we won't bind to a named parameter. Instead, a pair object gets passed as positional argument.
To work around this, we construct an anonymous hash that gets flattened into the argument list via prefix |.
As a bonus, here are some more creative ways to do it:
HTTP::Request.new(|%( %*ENV<REQUEST_METHOD REQUEST_URI> ));
HTTP::Request.new(|[=>] %*ENV<REQUEST_METHOD REQUEST_URI> );

How can I test :inclusion validation in Rails using RSpec

I have the following validation in my ActiveRecord.
validates :active, :inclusion => {:in => ['Y', 'N']}
I am using the following to test my model validations.
should_not allow_value('A').for(:active)
should allow_value('Y').for(:active)
should allow_value('N').for(:active)
Is there a cleaner and more through way of testing this? I am currently using RSpec2 and shoulda matchers.
EDIT
After some looking around I only found, this probably an 'ok' way of testing this, shoulda does not provide anything for this and anyone who requires it can write their own custom matcher for it.(And probably contribute it back to the project). Some links to discussions that might be intresting:
Links which indicate to the above . Link 1 , Link 2
should_ensure_value_in_range This one comes close to what can be used, but only accepts ranges and not a list of values. Custom matcher can be based on this.
Use shoulda_matchers
In recent versions of shoulda-matchers (at least as of v2.7.0), you can do:
expect(subject).to validate_inclusion_of(:active).in_array(%w[Y N])
This tests that the array of acceptable values in the validation exactly matches this spec.
In earlier versions, >= v1.4 , shoulda_matchers supports this syntax:
it {should ensure_inclusion_of(:active).in_array(%w[Y N]) }
If you have more elements to test than a boolean Y/N then you could also try.
it "should allow valid values" do
%w(item1 item2 item3 item4).each do |v|
should allow_value(v).for(:field)
end
end
it { should_not allow_value("other").for(:role) }
You can also replace the %w() with a constant you have defined in your model so that it tests that only the constant values are allowed.
CONSTANT = %w[item1 item2 item3 item4]
validates :field, :inclusion => CONSTANT
Then the test:
it "should allow valid values" do
Model::CONSTANT.each do |v|
should allow_value(v).for(:field)
end
end
I found one custom shoulda matcher (in one of the projects I was working on) which attempts to coming close to test something like this:
Examples:
it { should validate_inclusion_check_constraint_on :status, :allowed_values => %w(Open Resolved Closed) }
it { should validate_inclusion_check_constraint_on :age, :allowed_values => 0..100 }
The matcher tries to ensure that there is a DB constraint which blows up when it tries to save it.I will attempt to give the essence of the idea. The matches? implementation does something like:
begin
#allowed_values.each do |value|
#subject.send("#{#attribute}=", value)
#subject.save(:validate => false)
end
rescue ::ActiveRecord::StatementInvalid => e
# Returns false if the exception message contains a string matching the error throw by SQL db
end
I guess if we slightly change the above to say #subject.save and let Rails validation blow up, we can return false when the exception string contains something which close matches the real exception error message.
I know this is far from perfect to contributed back to the project, but I guess might not be a bad idea to add into your project as a custom matcher if you really want to test a lot of the :inclusion validation.

Group by using linq with NHibernate 3.0

As far as I know group by has only been added in NHibernate 3.0, but even when using version 3, I can't get group by to work.
I have tried to do the following query:
Session.Query().GroupBy(gbftr
=> gbftr.Tag).OrderByDescending(obftr => obftr.Count()).Take(count).ToList();
But I receive the following error:
Antlr.Runtime.NoViableAltException'. [. OrderByDescending (. GroupBy (NHibernate.Linq.NhQueryable `1 [Forum.Core.ForumTagRelation] Quote ((gbftr,) => (gbftr.Tag)),), Quote ((obftr,) => (. Count (obftr,))),)]
Does anyone have an idea if I might be mistaken, and group by isn't implemented in NHibernate 3.0, or who knows what I might be doing wrong?
GroupBy does work, but it's the combination with other operators that is causing trouble.
For example, this works:
session.Query<Foo>().GroupBy(x => x.Tag).Select(x => x.Count()).ToList();
But if you try to use Skip/Take to page, it fails.
In short: some constructs are not supported yet; you can use HQL for those. I suggest you open an issue at http://jira.nhforge.org