2

I am attempting to run my casperjs script by clicking a Run button in a website. My local set up is PHP 5.5.14 with Apache 2.4 on Windows7 [properly running; tested with php page]; and my question is: how do I properly install casperJS and phantomJS so that its PATH is recognized when I execute the script. I need to know what the path is in Windows to be able to use this: putenv("PHANTOMJS_EXECUTABLE=/usr/local/bin/phantomjs");. I have gone over the following possible solutions but none of them mention on how to properly install casperJS and phantomJS for the web server to recognize them: CasperJS passing data back to PHP, Pass parameter from php to casperjs/phantomjs, How to run casperJS script from php API, Using casperjs and PHP to save data, php execution phantom js works but casperjs does not work permission denied

This is my current script for multiple users to log-in to a page, log-out and then return how many successes/failures.

    var casper = require('casper').create()

    var colorizer = require('colorizer').create('Colorizer');

    var userNames = ['username1','username2','username3','username4', 'username5'];

    var passWords = ['password1','password2','password3','password4', 'password5'];

    var url = 'http://mywebsitenet.com';

    var tracker = {Success: [], Fail: []};

    function login(username, password) {
        casper.then(function () {
            this.sendKeys('#log', username);
            this.sendKeys('#pwd', password);
            this.click('#wpmem_login > form > fieldset > div.button_div > input.buttons');
    //      console.log(username + " has clicked the Log In button!")
        });

        casper.waitFor(function check() {
            return this.evaluate(function() {
                return document.getElementById('wp-admin-bar-logout');
            });
        }, function then() {    // step to execute when check() is ok
                this.click('#wp-admin-bar-logout > a'); 
                tracker.Success.push(username);
                this.echo(this.fetchText('#wp-admin-bar-my-account > a') + " you logged in.");
                this.capture('Success_'+username+'.png');       
        }, function timeout() { // step to execute if check has failed
            tracker.Fail.push(username);
            this.echo("Warning: " + username + " could not be logged in.", "WARNING");
            this.capture('Fail_'+username+'.png');
        });    
    };

    casper.start(); // empty page

    casper.viewport(1024, 768);

    userNames.forEach(function(username, index){
        casper.thenOpen(url); // open the start page
        login(username, passWords[index]); // schedule the steps
    });

    casper.then(function () {
                this.echo("Success: " + tracker.Success.length, "INFO");
                this.echo("Fail: " + tracker.Fail.length, "WARNING");
                this.echo(JSON.stringify(tracker));
            });

    casper.run(); // begin the execution
Community
  • 1
  • 1
gothamgator
  • 111
  • 1
  • 11
  • I think this is a windows-specific question, so I just added that tag. (Sorry, cannot answer myself.) – Darren Cook Jul 20 '14 at 21:19
  • I decided to switch to a Mac environment, but would still like to know what the correct install/PATH is to make this work like I did here (but in Windows): http://stackoverflow.com/questions/24856492/clicking-a-button-to-run-casperjs-in-php-and-echo-results-in-same-php-page-with – gothamgator Jul 21 '14 at 06:07

1 Answers1

1

So I ended up figuring out the proper path to casperJS and phantomJS. I placed both of the .exe in C:\casperjs\bin and did not even need to add them to my PATH, and it worked very well. This is my index.php, which sends AJAX for a php page executing my casperJ-script (I have added a counter for each successful/failed test, as well as allowed the user to select how frequently the test should run):

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="style.css" type="text/css" media="screen, projection"/>
        <link rel="shortcut icon" type="image/ico" href="favicon_jdoe.png" />
        <script src="jquery-2.1.1.min.js" type="text/javascript"></script>
        <script type="text/javascript" language="javascript" src="jquery.dropdownPlain.js"></script>
        <title>CasperJS Automated Testing Unit</title>
    </head>
    <center>
    <body>
    <div id="mainContent">
<p>Welcome to the CasperJS Automated Testing Unit</p>
<br>
  <button id="button_AJAX">Run CasperJS</button>
  <button id="button_STOP" onclick="myStopFunction()" style="display: none">Stop CasperJS</button>
    </div>

<p>
<select id="multi">
<option value="1">1 min</option>
<option value="2">2 min</option>
<option value="5">5 min</option>
<option value="10">10 min</option>
<option value="30" selected="selected">30 min</option>
<option value="60">1 hour</option>
<option value="360">6 hours</option>
<option value="720">12 hours</option>
<option value="1440">1 day</option>
</select>
</p>

<p>
    <div class="centered">
    <div style="float:left; margin-right:20px">
        <div style="float:left">Success count:</div>
        <div id="succcount" style="float:left">0</div> 
    </div>
    <div style="float:left">
        <div style="float:left">Fail count:</div>
        <div id="failcount" style="float:left">0</div>
    </div>
    </div>
</p>

    <br>

    <br>
    <div id="loading"></div>
<script type="text/javascript">

    var succcount = 0;
    var failcount = 0;

    $('#button_AJAX').click(function executecasperJS() {
       $('#loading').html('<img src="rays.gif"><br><i>Web harvesting in progress; please wait for test results.</i>');  // Loading image
            $.ajax({    // Run ajax request
            type: "GET",
            dataType: "text",
            url: "casperJS.php",
            success: function (data) {        
                    $('#loading').html(data);

                    if( data.indexOf('Fail: 0') !== -1 ) {
                        succcount++;
                    } else {
                        failcount++;
                    }
                    $('#succcount').html(succcount);
                    $('#failcount').html(failcount);
            }   
        });

multi = $( "#multi option:selected" ).val();
console.log("multi="+multi);        

timeout = setTimeout(executecasperJS,multi*60000); //1 min == 60000 
});
    $("#button_AJAX").click(function() {$("#button_AJAX").text("CasperJS Executed");});
    $("#button_STOP").click(function() {$("#button_AJAX").text("Run CasperJS");});
    function myStopFunction() {
        clearTimeout(timeout);
    } 

    $("#button_AJAX").click(function(){
       $("#button_STOP").show();
     });

     $("#button_STOP").click(function(){
        $("#button_STOP").hide();
      });

</script>
</div>
    <div id="page-wrap">
            <ul class="dropdown"> 
            <li><a href="#">CasperJS Logs</a>
                <ul class="sub_menu">
                     <li><a href="casperjs_log.txt" target="_blank">Testing Log</a></li>
                     <li><a href="casperjs_error.txt" target="_blank">Error Log</a></li>
        </ul>
    </div>
</center>
    </body>
</html> 

and here is the casperJS.php; which sends out an email if a failure occurs:

<?php

set_time_limit(3600);

date_default_timezone_set('America/New_York');
$date = date('m/d/Y h:i:s a', time());
$time_start = microtime(true);
$output = exec("C:\casperjs\bin\casperjs casperJScript.js");
    if (strpos($output, 'Fail: 0') === FALSE) {
        require_once('PHPMailer_5.2.4/class.phpmailer.php');
        $mail             = new PHPMailer();
        $mail->IsSMTP();     
        $mail->SMTPDebug  = 1;                   
        $mail->SMTPAuth   = true;                  
        $mail->SMTPSecure = "ssl";                
        $mail->Host       = "smtp.gmail.com";      
        $mail->Port       = 465;                   
        $mail->IsHTML(true);     
        $mail->Username   = "email@host.com";  
        $mail->Password   = "password";            
        $mail->SetFrom('email@host.co');
        $mail->AddReplyTo("email@host.co");
        $mail->Subject    = "casperJS: Server failure occured on $date";
        $mail->Body    = "The casperJS testing unit has picked up a server fault: $output
        $mail->AddAddress("email@host.co");
        if(!$mail->Send()) {
        //echo "Mailer Error: " . $mail->ErrorInfo;
        } else {
        //  echo "An error has occured and an email with the fault has been sent.";
        echo '<span style="color:#FF0000">An error has occured; it was logged and an email notification has been sent.</span>';
        $userip = $_SERVER['REMOTE_ADDR'];
        $file = 'casperjs_error.txt';
        $oldContents = file_get_contents($file);
        $fr = fopen($file, 'w');
        $txt = "ERROR log: $output. Requested by: $userip on $date." . PHP_EOL . PHP_EOL ;
        fwrite($fr, $txt);
        fwrite($fr, $oldContents);
        fclose($fr);    
        echo "<br />";
        echo "<br />";
        }
    }
    echo "Test Results: $output";
    $userip = $_SERVER['REMOTE_ADDR'];
    $time_end = microtime(true);
    $time = $time_end - $time_start;
    echo "<br />";
    echo "<br />";
    echo "Last test completed in $time seconds\n on $date";
    $file = 'casperjs_log.txt';
    $oldContents = file_get_contents($file);
    $fr = fopen($file, 'w');
    $txt = "Log: $output. Test completed in $time seconds\n on $date. Requested by: $userip" . PHP_EOL . PHP_EOL ;
    fwrite($fr, $txt);
    fwrite($fr, $oldContents);
    fclose($fr);        
?>
gothamgator
  • 111
  • 1
  • 11