I'm trying to write scripts in JavaScripts to test the UI of an iPhone app with MonkeyTalk. How do I use logic and conditionals with this? Right now I have a block:
if (this.app.button("name").verify())
do this if button exists
The problem is verify doesn't return a bool, it just throws an error in the test if the button doesn't exist. Is there a way to catch the error and run a script accordingly?
This seems to work :
function verifiedViewOrNull (view)
{
var exists = false;
try
{
view.verify();
exists = true;
}
catch (e)
{
}
return exists ? view : null;
}
and you can just call it as such :
if (verifiedViewOrNull(this.app.view("name")) != null
{
// It exists
} else
//doesn't exist, not gonna throw exception
Related
Is there a native way in codeception to just check for the presence of an element without failing the test if element is not found?
I see this answer which uses try/catch, but isn't there a native way of doing this?
try {
$this->seeElement($selector);
} catch (\PHPUnit_Framework_ExpectationFailedException $e) {
//
}
Looks like there's no other way, so here's a little function that you can use. Pass it valid xpath through $element and $I is your codeception object
/**
* If element is found return true if not return false
* #param $element
* #return bool
*/
public function elementIsPresent($I, $element)
{
try {
$I->seeElement($element);
$isFound = true;
} catch (\PHPUnit_Framework_ExpectationFailedException $e) {
$isFound = false;
}
return $isFound;
}
for simple text swap seeElement for see
I was trying to implement live typeface change's in the edittextview
based on markdown syntax
and the first code I do was
my_edit_text_view.text = makeMDStyleSpannable(my_edit_text_view.text)//returns spannableString
but no luck since it is not invoking every time when text is changed
so I gave another try which is creating listener and testing things are working properly before I jump
my_edit_text_view.text = doOnTextChanged { it, start, count,after ->
if (it != null) {
if(it.isNotEmpty()){
Toast.makeText(this, (makeMDStyleSpannable(it)), Toast.LENGTH_SHORT).show()
}else if(it.isNullOrEmpty()){
}
}
}
as result it worked on another TOAST
However, here's the real recurring happened
my_edit_text_view.text = doOnTextChanged { it, start, count,after ->
if (it != null) {
if(it.isNotEmpty()){
my_edit_text_view.text = (makeMDStyleSpannable(it)
}else if(it.isNullOrEmpty()){
}
}
}
umm, what actually happening is while there is external text change(keyboard) on the edittext it calls makeMDStyleSpannable and this apply internal change then again and again it will call doOnTextChanged, Finally crashes.
How could I solve this problem?
keyboard(onText added[external]) => startThelistner => makeMDStyleSpannable[in]
/\ ||
||=====[infinite]=======
thanks
You can solve it by adding a boolean to check if text is changed by user or the code.
val shouldIgnoreChange = false
my_edit_text_view.text = doOnTextChanged { it, start, count,after ->
if (it != null) {
if(it.isNotEmpty()){
if(!shouldIgnoreChange){
shouldIgnoreChange = true
my_edit_text_view.text = (makeMDStyleSpannable(it)
shouldIgnoreChange = false
}
}else if(it.isNullOrEmpty()){
}
}
}
I need to verify that a certain call is not made, when a previous method call throws an Exception.
// GIVEN
every { relaxedMock.eats() }.throws(NotHungryException())
// WHEN
sut.live()
// THEN
verify (exactly = 0) { relaxedMock2.sleeps() }
Problem with this code, it fails because of the Exception thrown and not because of the failed verification.
I understand that your WHEN block will always throw an exception.
In that case you have multiple options from my point of view:
Simple plain Kotlin. Wrap the WHEN block with a try-catch block, e.g. like this:
// GIVEN
every { relaxedMock.eats() }.throws(NotHungryException())
// WHEN
var exceptionThrown: Boolean = false
try {
sut.live()
} catch(exception: NotHungryException) {
// Maybe put some assertions on the exception here.
exceptionThrown = true
}
assertTrue(exceptionThrown)
// THEN
verify (exactly = 0) { relaxedMock2.sleeps() }
For a bit nicer code, you can use JUnit5 API's Assertions. assertThrows will expect an exception being thrown by a specific piece of code. It will fail the test, if no exception is thrown. Also it will return the thrown exception, for you to inspect it.
import org.junit.jupiter.api.Assertions
// GIVEN
every { relaxedMock.eats() }.throws(NotHungryException())
// WHEN
val exception = Assertions.assertThrows(NotHungryException::class.java) { sut.live() }
// THEN
verify (exactly = 0) { relaxedMock2.sleeps() }
If you're using Kotest you can use the shouldThrow assertion. Which also allows you to retrieve the thrown exception and validate its type.
import io.kotest.assertions.throwables.shouldThrow
// GIVEN
every { relaxedMock.eats() }.throws(NotHungryException())
// WHEN
val exception = shouldThrow<NotHungryException> { sut.live() }
// THEN
verify (exactly = 0) { relaxedMock2.sleeps() }
I had similar issue and found that my method is not surrounded by try catch. This mean the method will always throw exception.
Test
The unit test to verify the result when the following method is called while stubbing it with predefine Exception
#Test
fun returnSearchError() {
every { searchService.search(query) }.throws(BadSearchException())
val result = searchRepository.search(query)
assertEquals(SearchStates.SearchError, result)
}
Faulty code
fun search(query: String): SearchStates {
val result = searchService.search(query) // No try catch for the thrown exception
return try {
SearchStates.MatchingResult(result)
} catch (badSearchException: BadSearchException) {
SearchStates.SearchError
}
}
Refactored it to
fun search(query: String): SearchStates {
return try {
val result = searchService.search(query)
SearchStates.MatchingResult(result)
} catch (badSearchException: BadSearchException) {
SearchStates.SearchError
}
}
I am trying to find an element in the else block, if the condition in the if block doesn't work.
try
{
if(Driver.driver.findElement(By.xpath("//div[#id='Tpay_success']")).isDisplayed())
{
System.out.println("Payment is successful");
Reporter.log("Payment is successful");
}
else
{
Thread.sleep(2000);
{
if(Driver.driver.findElement(By.id("pay_decline")).isEnabled())
{
System.out.println("pay declined");
action.moveToElement(By.id("pay_decline")).isEnabled()).click().perform();
Reporter.log("PAYMENT DECLINED!!");
}
}
catch(ExceptionInInitializerError ex)
{
System.out.println(ex);
}
}
I am getting an error saying:
Unable to locate element: {"method":"xpath","selector":"//div[#id='Tpay_succes']"}
I want the else block to be executed if the if block doesn't get executed.
Any suggestions are welcome. Thanks.
if(Driver.driver.findElement(By.xpath("//div[#id='Tpay_success']")).isDisplayed())
This doesn't work the way you think it does. findElement() will throw an error if the element is not present in the DOM of the currently loaded page. This means that isDisplayed() will not be called in such a case.
You can do what you want with a try...catch:
try
{
Driver.driver.findElement(By.xpath("//div[#id='Tpay_success']"))
System.out.println("Payment is successful");
Reporter.log("Payment is successful");
} catch(ExceptionInInitializerError ex) {
Thread.sleep(2000);
if(Driver.driver.findElement(By.id("pay_decline")).isEnabled()) {
System.out.println("pay declined");
action.moveToElement(By.id("pay_decline")).isEnabled()).click().perform();
Reporter.log("PAYMENT DECLINED!!");
}
}
Note that you should learn about how to make the selenium driver wait for a specific element rather than using Thread.sleep().
I have a problem with UploadImageBehavior.
I need to create simple button on frontend part that allow me to remove image (user avatar) after model save.
Actually i know how to do it with unlink, but i absolutely don't understand how to do that via behaviour.
I have next code in rules:
[['avatar'], 'file', 'skipOnEmpty' => true, 'extensions' => 'png, jpg, jpeg'],
So Yii just ignore me, if i try to pass null to my avatar property.
Thx )
Just create a method to your model class that does the unlinking, sets the file attribute in your model to null and saves the model.
public function removeAvatar() {
$transaction = $this->getDb()->beginTransaction();
try {
// If this is a new record throw an Exception because no file has been uploaded yet
if($this->isNewRecord) {
throw new \Exception("Can't delete file of new record");
}
// Set the attribute avatar to null
$this->avatar = null;
// Try to save the record. If we can't then throw an Exception
if(!$this->save()) {
throw new \Exception("Couldn't save the model");
}
// Try to delete the file. If we can't then throw an Exception
if(!unlink(Yii::getAlias('#app/path/to/your/file.something')) {
throw new \Exception("Couldn't delete the file");
}
$transaction->commit();
return true;
}
catch(\Exception $e) {
$transaction->rollback();
return false;
}
}
Below works for me:
unlink(getcwd().'/uploads/'.$model->file_id.'/'.$fileModel->file_name.$fileModel->extension);
getcwd() gets the current working directory. The docs for it are here