How create my own assertions for casperJS - casperjs

Is there a way to create custom assertions for casperJS? The only thing that I got worked is something like this:
casper.test.assertIsChecked = function(selector, msg) {
var isChecked = !this.casper.getElementsAttribute(selector, 'checked')
this.assertTruthy(isChecked, msg);
}
But its a bit hacky to just add it to test object and it lacks from proper error message.

Related

How do I call a javascript function from Go/WASM using Invoke that acts upon a js.Value?

I need to check for fullscreen support with my Go WASM Canvas project, before switching to fullscreen mode. I have the following code so far:
var fullscreenFunc js.Value
var fullscreenNotSupported bool
set with the following logic:
fullscreenFunc = app.Get("requestFullscreen")
if fullscreenFunc.IsUndefined() {
fullscreenFunc = app.Get("mozRequestFullScreen")
if fullscreenFunc.IsUndefined() {
fullscreenFunc = app.Get("webkitRequestFullscreen")
if fullscreenFunc.IsUndefined() {
fullscreenFunc = app.Get("msRequestFullscreen")
if fullscreenFunc.IsUndefined() {
fullscreenNotSupported = true
println("Fullscreen not supported")
}
}
}
}
I was expecting to be able to call the correct function with js.Invoke, but I see no way to tell the Invoke upon which object the call should be made. My 'app' value is being interpreted just as a param.
func Fullscreen(app js.Value) {
if fullscreenNotSupported {
return
}
fullscreenFunc.Invoke(app)
}
resulting in:
panic: JavaScript error: 'mozRequestFullScreen' called on an object that does not implement interface Element.
So am I correct in my thinking that the only way I can call the correct method, is not to store the Function, but to store a string of the function name, and then 'invoke' / 'call' it using the following approach?
app.Call(fullscreenFunctionNameString)
It feels like I misunderstood the purpose of Invoke. Is it only for js.Global() type calls?
[edit] Using 'Call', at least it seems possible to derive the function name without having to repeat the above browser specifics:
fullscreenFunctionName = fullscreenFunc.Get("name").String()
app.Call(fullscreenFunctionNameString)
It doesn't answer the question, but is probably of help to someone trying to do the same.
The arguments to invoke get turned into arguments for the javascript function it wraps. Since those fullscreen functions don't need any arguments, I think you might just need to change:
fullscreenFunc.Invoke(app)
To:
fullscreenFunc.Invoke()
...assuming app is the same JS element in both places. If not your Call solution is probably your best bet.

Amazon IAP Plugin for Xamarin - crash when using TaskCompletionSource

I'm trying to implement a wrapper for the Amazon IAP Plugin for Xamarin. It uses an event based system in the following way:
You can initiate method calls and listen for events. Method calls initiate requests, some of which return a response. Events are asynchronous system-generated messages that are sent in response to method calls to return the requested data to you.
See more here
My goal is to wrap this event based system into some API which allows me to use the plugin with tasks, so I can use the async-await syntax. To achieve that I'm using the TaskCompletionSource like in the following example:
public async Task<bool> GetProductInfoAsync(params string[] productIds)
{
var iapService = AmazonIapV2Impl.Instance;
var tcs = new TaskCompletionSource<bool>();
var skus = new SkusInput { Skus = productIds.ToList() };
var requestId = iapService.GetProductData(skus).RequestId;
GetProductDataResponseDelegator delegator = null;
delegator = new GetProductDataResponseDelegator(response =>
{
if(response.Id == requestId) {
var result = GetResultFromResponse(response);
tcs.SetResult(result);
//iapService.RemoveGetProductDataResponseListener(delegator.responseDelegate);
}
});
iapService.AddGetProductDataResponseListener(delegator.responseDelegate);
return await tcs.Task;
}
This code seems to work fine if the method gets called once, but if it gets called two times in a row the app crashes immediately and the only thing printed to the console is the following message..
[mono] Unhandled Exception:
[mono] System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
[mono-rt] [ERROR] FATAL UNHANDLED EXCEPTION: System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
..which kinda makes no sense at all.
So is there something obvious I'm missing here? Or could it be a bug from the plugin?
I have created a repository with the code above so you can reproduce the problem. It's my playground, so please ignore the whole structure of the project and just focus on the classes AmazonIAPService and MainActivity.
Hint 1:
The commented line //iapService.RemoveGetProductDataResponseListener(delegator.responseDelegate); causes also a crash with the same message but already at the first call of the method.
Hint 2:
The AmazonIAPService contains a commented method which uses await Task.Delay(TimeSpan.FromMilliseconds(1)) and solves the problem from above in a very hacky way which I really don't like.
Problem seems to be that those functions have to run asynchronously. Also mentioned here in the doc. So once you run those functions synchronously somehow they throw exception, i dont what is happening in the library but your hacky solution is the actual solution for that. If you write the function as below. it also works.
PurchaseResponseDelegator delegator = null;
delegator = new PurchaseResponseDelegator(async response =>
{
await Task.Run(() =>
{
if (response.RequestId == requestId)
{
var result = GetPurchaseEventHandler(response);
var sucess = taskCompletionSource.TrySetResult(result);
context.RemovePurchaseResponseListener(delegator.responseDelegate);
}
} );
});
// Register for an event
context.AddPurchaseResponseListener(delegator.responseDelegate);
One other exception I had despite the async-await solution, somehow, it always throws exception for the line taskCompletionSource.SetResult(result); for PurchaseUpdates functions only. if i use instead this line var sucess = taskCompletionSource.TrySetResult(result); it works fine

Cannot pass ampersand and hash sign in MVC

I have this code
#using (Ajax.BeginForm("LoadFilter", "Contact", new { filterType = (int)FilterContactBy.Name }, new AjaxOptions { OnBegin = "ShowProgrees", OnSuccess = "HideProgress" }))
{
#Html.TextBoxFor(m => m.ContactFilter.FilterValue, new { placeholder = "Enter a name" })
<input type="submit" class="link submit green" value="Add Filter" />
}
As quite obvious, the ShowProgress and HideProgress method do nothing but show and hide a loader gif.
The method at backend is
[HttpPost]
public ActionResult LoadFilter(ContactListModel filter, int filterType=0, Boolean isAllFilterApply=true)
{
if (filter != null)
{
// process here
}
}
It works fine if I enter anything, for example
hi
test
me & you
contact #1
contact #1 and me
BUT
When I enter &# together in any from error occurs. The loader gif just keeps moving and the code on Controller is never hit.
Also, in Chrome console, it shows 500 Internal Server Error (and so does Firefox!).
My Solution
I tried escape and enocodeURIComponent but it didn't worked. Here's the method I tried
$.ajaxPrefilter(function(o, org, xhr) {
if (org.url.indexOf('/Contact/LoadFilter?filterType=') > -1) {
// console.log(org.data[0].value);
org.data[0].value = encodeURIComponent(org.data[0].value);
// console.log(org.data[0].value);
}
});
The output (in console)
&#
%26%23
When instead of encodeURIComponent I used escape, the output was same
&#
%26%23
But it still doesn't hit the method on controller. Can anyone please help me to get a solution, and more importantly, tell me why is this occurring in the first place?
ps
Please don't ask me that what is the use of inputting &# in a contact filter, or to remove these and tell client this is not a valid input. I can't do that, so please don't advice that.
Update
Is anyone even reading this fully? I am not asking that how can I decode. NO. Please read the full question before marking it as duplicate or marking it for close.
Okay, I got this.
I created Application_BeginRequest in Global.asax in the code like this..
protected void Application_BeginRequest(Object sender, EventArgs e)
{
var httpApp = (HttpApplication)sender;
Debug.Write(httpApp);
}
I sat a breakpoint of httpApp and then in the watch window, checked for httpApp.Request and found that it was there. It said (something I don't remember right now) threw an exception of type 'System.Web.HttpRequestValidationException'.
So, I got that the error was because of this, so on the method LoadFilter, I just added the attribute ValidateInput(false), and it's working
[HttpPost]
[ValidateInput(false)]
public ActionResult LoadFilter(ContactListModel filter, int filterType=0, Boolean isAllFilterApply=true)
{
// process here
}
Though, I do have to check for sql injection in here because we are building up a dynamic query from the input we receive.
Use
HttpUtility.UrlDecode("url")

Trying to use Rhino Mocks in VS2010 -- tests don't run

I have a unit test that works just fine when it is hitting a real object that hits teh real data storage. Something like that:
[TestMethod]
public void ATest()
{
var p = new Provider();
var data = p.GetData();
...
}
This test gets executed in all modes, gets the data back and does everything that is exected from it. Now, say I want to mock the provider using Rhino Mocks. Provider class implements IProvider. So I go and write something like this:
[TestMethod]
public void ATest()
{
var p = MockRepository.GenerateStub<IProvider>();
...
var data = p.GetData();
...
}
But now when I try to debug this test, it doesn't work. At all. I mean, I put a breakpoint on the first line of this method (on the '{' itself) and it is not being hit. Kind of weird...
I am all new to Rhino Mocks, maybe I am missing something obvious?
You didn't define a return value for the GetData call on the mock. Try something like this:
p.Stub(s => s.GetData()).Return(testData);

Should a method should be throwing an exception to the Unit Test?

I have a simple method for sending emails:
public void notifyEmail(string messageSubject, string messageBody)
{
MailMessage message = new MailMessage(from, to);
message.Subject = messageSubject;
message.Body = messageBody;
SmtpClient client = new SmtpClient(smtp_client);
client.Send(message);
message.Dispose();//release everything related
}
And a unit test (I'm learning):
[TestMethod()]
public void notifyEmailTest()
{
eMail target = new eMail("TEST Subject","TEST Body"); // TODO: Initialize to an appropriate value
bool testSent = true;
try
{
target.notifyEmail();
}
catch (Exception)
{
testSent = false;
}
Assert.IsTrue(testSent);
}
I deliberately set the smtp_client variable value to something invalid.
Running the code in my project results in an error.
Running the test method results in a Pass. Should my test or method be structured differently so that errors will fail the test?
I always do everything I can to avoid putting try-catch clauses on my unit tests. Instead try using the ExpectedException attribute (the attribute is the same for NUnit and MSTest) and set the type to the exception you are expecting i.e.
[TestMethod]
[ExpectedException(typeof(NetworkException))]
public void ShouldThrowNetworkExceptionIfSmtpServerIsInvalid)
{
//... test code here.
}
Another approach that I have used is to create a static class with an AssertExpectedException method since sometimes a method can throw the same type of exception for different reasons and the only way to know for sure if the accurate message is being returned is with custom code since the attribute does not assert the message the thrown exception is returning.
Hope this helps.
Regards.
If you expect that target.notifyEmail() should be throwing an exception, then that's what you should be testing for. If you were using NUnit you could use Assert.Throws<T>, e.g.
[Test]
public void notifyEmailTestFails()
{
// TODO: Initialize to an appropriate value
eMail target = new eMail("TEST Subject","TEST Body");
Assert.Throws<InvalidOperationException>(target.notifyEmail());
}
However, now I see you're using VSUnit you should be using [ExpectedException(typeof(...))]
as mentioned in other answers.
In general you should have separate tests for success, failure, and for exception conditions.
The way I normally do this is to decorate the test with ExpectedException (
http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.expectedexceptionattribute(v=vs.80).aspx)
. But you want to catch something MUCH less generic than "Exception."
If you don't want to use expected exception, then instead of:
bool testSent = true;
try
{
target.notifyEmail();
}
catch (Exception)
{
testSent = false;
}
Assert.IsTrue(testSent);
You can be a little less verbose:
try{
target.notifyEmail();
Assert.Fail("Expected an exception here");
}
catch (SmtpException){
}
I would highly recommend you to try the FluenAssertions:
http://fluentassertions.codeplex.com/
They are simple awesome and Elegant
And they let you check the exception message (You can not do that with the ExpectedException attribute)
Example:
using FluentAssertions;
[TestMethod]
public void notifyEmailTest()
{
eMail target = new eMail("TEST Subject","TEST Body"); // TODO: Initialize to an appropriate value
target.Invoking(x => x.notifyEmail())
.ShouldThrow<YourExcpectedException>()
.WithMessage("Your expected message", FluentAssertions.Assertions.ComparisonMode.Substring);
}

Resources