I was going through a tutorial, on PHPUNIT i got the tutorial quit well...and do some logins
on my own..
But i went into the web to load a page and submit a value on a real-time page
it works fine... but the issue i have is that after entering the user key ..it submit but it wont wait for the next page
I see similar questions here but none is working-out for me
Pls Can anyone help me.
This is my code
<?php
class TestLogin extends PHPUnit_Extensions_Selenium2TestCase {
public function setUp()
{
$this->setHost('localhost');
$this->setPort(4444);
$this->setBrowser('firefox');
$this->setBrowserUrl('http://localhost/tutor');
}
public function setSpeed($timeInMilliSec)
{
$this->setSpeed('120');
}
/*Function to locate website*/
public function testHasLoginForm()
{
$this->url('http://www.jamb.org.ng/DirectEntry/');/*This is the site*/
$username = $this->byId('ctl00_ContentPlaceHolder1_RegNumber');/*Search for a name*/
##ctl00_ContentPlaceHolder1_txtRegNumber
$action = $this->byId('ctl00_ContentPlaceHolder1_Reprint')->attribute('action');
$this->byId('ctl00_ContentPlaceHolder1_RegNumber')->value('49130518ED');/*value of the textbox*/
$jump = $this->byId('ctl00_ContentPlaceHolder1_Reprint');
$jump->submit();
}
}
?>
You could use
$this->timeouts()->implicitWait(10000);//10 seconds
to set timeout of searching elements on page.
https://github.com/sebastianbergmann/phpunit-selenium/blob/master/PHPUnit/Extensions/Selenium2TestCase/Session/Timeouts.php
Resolved.i just changed
$jump->submit();
to
$this->byName('ctl00$ContentPlaceHolder1$Reprint')->click();
If you want to wait for diffrent elements or even capabilities i suggest use this pattern
This is example wait for element. I recommend using byCssSelector here to get more flexibility.
You can easily use this pattern for example to wait for element to be clickable:
protected function waitForClickable($element, $wait=30) {
for ($i=0; $i <= $wait; $i++) {
try{
$element->click();
return true;
}
catch (Exception $e) {
sleep(1);
}
}
return false;
}
You can even use it in any context passing anonymous function as parameter:
protected function waitForAny($function, $args, $wait=30) {
for ($i=0; $i <= $wait; $i++) {
try{
call_user_func_array($function, $args);
return true;
}
catch (Exception $e) {
sleep(1);
}
}
return false;
}
Usage:
$f = function($e){
$e->click();
};
$this->waitForAny($f, array($element));
Related
I was trying to use com_event_sink, I came across a problem
Here is a example from php.net
<?php
class IEEventSinker {
var $terminated = false;
function ProgressChange($progress, $progressmax) {
echo "Download progress: $progress / $progressmax\n";
}
function DocumentComplete(&$dom, $url) {
echo "Document $url complete\n";
}
function OnQuit() {
echo "Quit!\n";
$this->terminated = true;
}
}
$ie = new COM("InternetExplorer.Application");
// note that you don't need the & for PHP 5!
$sink = new IEEventSinker();
com_event_sink($ie, $sink, "DWebBrowserEvents2");
$ie->Visible = true;
$ie->Navigate("http://www.example.org");
while(!$sink->terminated) {
com_message_pump(4000);
}
$ie = null;
?>
In the line
com_event_sink($ie, $sink, "DWebBrowserEvents2");
I know the interface used to perform event sink is "DWebBrowserEvents2".
My question is,
Is there anyway that I can view the interface of a COM object?
Since I only got an OCX file with no documentation, I have no idea how to find the interface. Thanks
I am using PHP Memcached & when I delete a key, I can still retrieve the key. What could I be doing wrong?
function __construct() {
$this->_cache = array();
// if we have memcache support, load it from CACHE_POOL
//
if (class_exists('Memcached')) {
$this->_mc = new Memcached('CACHE_POOL');
$servers = $this->_mc->getServerList();
if (empty($servers)) {
//This code block will only execute if we are setting up a new EG(persistent_list) entry
$this->_mc->setOption(Memcached::OPT_RECV_TIMEOUT, 1000);
$this->_mc->setOption(Memcached::OPT_SEND_TIMEOUT, 3000);
$this->_mc->setOption(Memcached::OPT_TCP_NODELAY, true);
$this->_mc->setOption(Memcached::OPT_PREFIX_KEY, "md_");
$this->_mc->addServers(self::$_MEMCACHE_IPS);
}
$current_cache = $this->_mc->get(self::CACHE_KEY);
if ($current_cache) {
$this->_cache = array_merge($this->_cache, $current_cache);
}
}
}
function delete($key) {
self::instance()->_mc->delete($key);
}
function getSafe($key) {
return isset($this->_cache[$key]) ? $this->_cache[$key] : FALSE;
}
self::instance()->delete("test");
echo(self::instance()->getSafe("test"));
After running this, the get still returns a value. Not sure what is going on here.
You should also delete cache from _cache property in terms of the retrieving method:
function delete($key) {
self::instance()->_mc->delete($key);
unset(self::instance()->_cache[$key]);
}
But do not apply this code design in your production environment.
I'm using a Contract form from HTML Contract Form Guide in my website. In testing, I am running my website from my computer using apache and PHP v5.5. Everything seems to work well on my testing server and I can fill out the form, click submit, and land on the "success page". When I upload my site to my hosting service and try to use the contact form, the captcha does not accept my input and returns the message, "failed the anti-spam check". My hosting service is running PHP v5.3. I'm not sure what's changing and why my form no longer works when I upload it. Oh, I am also learning PHP on the fly so I might not fully comprehend what I am being asked so it might take me a little longer to give an accurate reply.
* This issue was solved. I ended up contacting fatcow which is my hosting company. This is their response "I have set the session.save_path in your 'PHP Scripting' and I have increased the memory limit from 32 MB to 128 MB for your PHP scripts." I guess it was a server side issue. I guess I've narrowed it down and when I run to a similar issue I can also assume it is a server side issue. Hope anyone with a similar issue can use this post and decide what to do accordingly.
I ran var_dump() on $_SESSION['FGCF_Captcha_Answer'] and $user_answer and both values were equal. This is what I got:
string 'c85757e710d687d24c0b044812d5ee05' (length=32)
string 'c85757e710d687d24c0b044812d5ee05' (length=32)
I am also hosting from a fatcow server and have contacted them to see if they know anything about this issue with reCAPTCHA on their server. Just awaiting their reply. Is it possible that the server I'm running on could experience these things, maybe not a programming question but like I stated above, on my own computer running with apache the form works fine and the only problem I'm having on fatcow is not the entire form, just reCAPTCHA
Here is the captcha code, if anything else is needed please let me know:
<?PHP
class FGSimpleCaptcha extends FG_CaptchaHandler
{
var $error_str;
var $captcha_varname;
var $uniquekey;
function FGSimpleCaptcha($captcha_var_name)
{
$this->captcha_varname=$captcha_var_name;
$this->uniquekey='KHJhsjsy65HGbsmnd';
}
/*Add more simple questions here.*/
function GetSimpleCaptcha()
{
$arrQuestions = array(
"What color is the sky? "=>"blue",
"What is 1+1=" => "2",
"What is the color of grass?"=>"green",
"Are you a robot? "=>"no",
"Are you human?"=>"yes");
$question = array_rand($arrQuestions);
$answer = $arrQuestions[$question];
$_SESSION['FGCF_Captcha_Answer'] = $this->Md5CaptchaAnswer($answer);
return $question;
}
function SetFormKey($key)
{
$this->uniquekey = $key;
}
function GetKey()
{
return $this->uniquekey;
}
function Validate()
{
$ret=false;
if(empty($_POST[$this->captcha_varname]))
{
$this->error_str = "Please answer the anti-spam question";
$ret = false;
}
else
{
$scaptcha = trim($_POST[$this->captcha_varname]);
$scaptcha = strtolower($scaptcha);
$user_answer = $this->Md5CaptchaAnswer($scaptcha);
if($user_answer != $_SESSION['FGCF_Captcha_Answer'])
{
$this->error_str = "Failed the anti-spam check!";
$ret = false;
}
else
{
$ret = true;
}
}//else
return $ret;
}
function Md5CaptchaAnswer($answer)
{
return md5($this->GetKey().$answer);
}
function GetError()
{
return $this->error_str;
}
}
?>
Here is partial code for the form:
class FGContactForm
{
var $receipients;
var $errors;
var $error_message;
var $name;
var $email;
var $message;
var $from_address;
var $form_random_key;
var $conditional_field;
var $arr_conditional_receipients;
var $fileupload_fields;
var $captcha_handler;
var $mailer;
function FGContactForm()
{
$this->receipients = array();
$this->errors = array();
$this->form_random_key = 'HTgsjhartag';
$this->conditional_field='';
$this->arr_conditional_receipients=array();
$this->fileupload_fields=array();
$this->mailer = new PHPMailer();
$this->mailer->CharSet = 'utf-8';
}
function EnableCaptcha($captcha_handler)
{
$this->captcha_handler = $captcha_handler;
session_start();
}
function AddRecipient($email,$name="")
{
$this->mailer->AddAddress($email,$name);
}
function SetFromAddress($from)
{
$this->from_address = $from;
}
function SetFormRandomKey($key)
{
$this->form_random_key = $key;
}
function GetSpamTrapInputName()
{
return 'sp'.md5('KHGdnbvsgst'.$this->GetKey());
}
function SafeDisplay($value_name)
{
if(empty($_POST[$value_name]))
{
return'';
}
return htmlentities($_POST[$value_name]);
}
function GetFormIDInputName()
{
$rand = md5('TygshRt'.$this->GetKey());
$rand = substr($rand,0,20);
return 'id'.$rand;
}
function GetFormIDInputValue()
{
return md5('jhgahTsajhg'.$this->GetKey());
}
function SetConditionalField($field)
{
$this->conditional_field = $field;
}
function AddConditionalReceipent($value,$email)
{
$this->arr_conditional_receipients[$value] = $email;
}
function AddFileUploadField($file_field_name,$accepted_types,$max_size)
{
$this->fileupload_fields[] =
array("name"=>$file_field_name,
"file_types"=>$accepted_types,
"maxsize"=>$max_size);
}
function ProcessForm()
{
if(!isset($_POST['submitted']))
{
return false;
}
if(!$this->Validate())
{
$this->error_message = implode('<br/>',$this->errors);
return false;
}
$this->CollectData();
$ret = $this->SendFormSubmission();
return $ret;
}
function RedirectToURL($url)
{
header("Location: $url");/* Redirect browser */
/* Make sure that code below does not get executed when we redirect. */
exit;
}
function GetErrorMessage()
{
return $this->error_message;
}
function GetSelfScript()
{
return htmlentities($_SERVER['PHP_SELF']);
}
function GetName()
{
return $this->name;
}
function GetEmail()
{
return $this->email;
}
function GetMessage()
{
return htmlentities($this->message,ENT_QUOTES,"UTF-8");
}
This issue was solved. I ended up contacting fatcow which is my hosting company. This is their response "I have set the session.save_path in your 'PHP Scripting' and I have increased the memory limit from 32 MB to 128 MB for your PHP scripts." I guess it was a server side issue. With some help I was able to narrow it down and when I run to a similar issue I can also assume it is a server side issue. Hope anyone with a similar issue can use this post and decide what to do accordingly.
The script works fine and is setting the data, but the website code is unable to use it and is instead setting its own memcached values. My website code is written in codeIgniter framework. I don't know why this is happening.
My script code :-
function getFromMemcached($string) {
$memcached_library = new Memcached();
$memcached_library->addServer('localhost', 11211);
$result = $memcached_library->get(md5($string));
return $result;
}
function setInMemcached($string,$result,$TTL = 1800) {
$memcached_library = new Memcached();
$memcached_library->addServer('localhost', 11211);
$memcached_library->set(md5($string),$result, $TTL);
}
/*---------- Function stores complete product page as one function call cache -----------------*/
function getCachedCompleteProduct($productId,$brand)
{
$result = array();
$result = getFromMemcached($productId." product page");
if(true==empty($result))
{
//------- REST CODE storing data in $result------
setInMemcached($productId." product page",$result,1800);
}
return $result;
}
Website Code :-
private function getFromMemcached($string) {
$result = $this->memcached_library->get(md5($string));
return $result;
}
private function setInMemcached($string,$result,$TTL = 1800) {
$this->memcached_library->add(md5($string),$result, $TTL);
}
/*---------- Function stores complete product page as one function call cache -----------------*/
public function getCachedCompleteProduct($productId,$brand)
{
$result = array();
$result = $this->getFromMemcached($productId." product page");
if(true==empty($result))
{
// ----------- Rest Code storing data in $result
$this->setInMemcached($productId." product page",$result,1800);
}
return $result;
}
This is saving data in memcached. I checked by printing inside the if condition and checking the final result
Based on the CodeIgniter docs, you can make use of:
class YourController extends CI_Controller() {
function __construct() {
$this->load->driver('cache');
}
private function getFromMemcached($key) {
$result = $this->cache->memcached->get(md5($key));
return $result;
}
private function setInMemcached($key, $value, $TTL = 1800) {
$this->cache->memcached->save(md5($key), $value, $TTL);
}
public function getCachedCompleteProduct($productId,$brand) {
$result = array();
$result = $this->getFromMemcached($productId." product page");
if( empty($result) ) {
// ----------- Rest Code storing data in $result
$this->setInMemcached($productId." product page",$result,1800);
}
return $result;
}
}
Personally try to avoid 3rd party libraries if it already exists in the core framework. And I have tested this, it's working superbly, so that should fix this for you :)
Just remember to follow the instructions at http://ellislab.com/codeigniter/user-guide/libraries/caching.html#memcached to set the config as needed for the memcache server
I have users' table users, where I store information like post_count and so on. I want to have ~50 badges and it is going to be even more than that in future.
So, I want to have a page where member of website could go and take the badge, not automatically give him it like in SO. And after he clicks a button called smth like "Take 'Made 10 posts' badge" the system checks if he has posted 10 posts and doesn't have this badge already, and if it's ok, give him the badge and insert into the new table the badge's id and user_id that member couldn't take it twice.
But I have so many badges, so do I really need to put so many if's to check for all badges? What would be your suggestion on this? How can I make it more optimal if it's even possible?
Thank you.
optimal would be IMHO the the following:
have an object for the user with functions that return user specific attributes/metrics that you initialise with the proper user id (you probably wanna make this a singleton/static for some elements...):
<?
class User {
public function initUser($id) {
/* initialise the user. maby load all metrics now, or if they
are intensive on demand when the functions are called.
you can cache them in a class variable*/
}
public function getPostCount() {
// return number of posts
}
public function getRegisterDate() {
// return register date
}
public function getNumberOfLogins() {
// return the number of logins the user has made over time
}
}
?>
have a badge object that is initialised with an id/key and loads dependencies from your database:
<?
class Badge {
protected $dependencies = array();
public function initBadge($id) {
$this->loadDependencies($id);
}
protected function loadDependencies() {
// load data from mysql and store it into dependencies like so:
$dependencies = array(array(
'value' => 300,
'type' => 'PostCount',
'compare => 'greater',
),...);
$this->dependencies = $dependencies;
}
public function getDependencies() {
return $this->dependencies;
}
}
?>
then you could have a class that controls the awarding of batches (you can also do it inside user...)
and checks dependencies and prints failed dependencies etc...
<?
class BadgeAwarder {
protected $badge = null;
protected $user = null;
public function awardBadge($userid,$badge) {
if(is_null($this->badge)) {
$this->badge = new Badge; // or something else for strange freaky badges, passed by $badge
}
$this->badge->initBadge($badge);
if(is_null($this->user)) {
$this->user = new User;
$this->user->initUser($userid);
}
$allowed = $this->checkDependencies();
if($allowed === true) {
// grant badge, print congratulations
} else if(is_array($failed)) {
// sorry, you failed tu full fill thef ollowing dependencies: print_r($failed);
} else {
echo "error?";
}
}
protected function checkDependencies() {
$failed = array();
foreach($this->badge->getDependencies() as $depdency) {
$value = call_user_func(array($this->badge, 'get'.$depdency['type']));
if(!$this->compare($value,$depdency['value'],$dependency['compare'])) {
$failed[] = $dependency;
}
}
if(count($failed) > 0) {
return $failed;
} else {
return true;
}
}
protected function compare($val1,$val2,$operator) {
if($operator == 'greater') {
return ($val1 > $val2);
}
}
}
?>
you can extend to this class if you have very custom batches that require weird calculations.
hope i brought you on the right track.
untested andp robably full of syntax errors.
welcome to the world of object oriented programming. still wanna do this?
Maybe throw the information into a table and check against that? If it's based on the number of posts, have fields for badge_name and post_count and check that way?