Using Selenium RC With Multiple Users

March 13th, 2008

So you may be testing with selenium already, you may even be using selenium RC to automate your testing and integrate it with your other unit tests, and you may already be doing so in a shared development environment, but if you aren’t using selenium RC with multiple users, you may not know that you can start the RC server on any port you wish, allowing multiple clients to connect at the same time.

To start the selenium RC server, you would typically run this command:

java -jar selenium-server.jar

Which will start it on the default port of 4444. If you want to start it on another port, simply add -port <portnumber> to the command like this:

java -jar selenium-server.jar -port 1234

This command would start the server on port 1234.

Great, now I can start the server on multiple ports, so what?

So here is the good news for those of us in shared development environments. Say you have a windows virtual machine running selenium with your test browser installed. Things get complicated when multiple clients are testing at the same time. Tests can fail unexpectedly, developers begin fighting for time on the test server, and all hell breaks loose. By running multiple servers on different ports, we can avoid the third world war. Everyone can connect at the same time to their personal server, and we have peace and harmony in our testing environment.

Wow, setting up a different port everytime must suck.

Not really. There are many ways that you can automate the process so that it’s completely transparent to your development team. A lot will depend on your environment, but in our case, we created a .bat file that starts the servers in our virtual machine and placed it in the start-up folder.

start "Selenium 4444" /min java.exe -jar selenium-server.jar -port 4444
start "Selenium 4445" /min java.exe -jar selenium-server.jar -port 4445
start "Selenium 4446" /min java.exe -jar selenium-server.jar -port 4446
start "Selenium 4447" /min java.exe -jar selenium-server.jar -port 4447

HTML code generated by vim-color-improved v.0.3.2.

With this in place, we now have 4 selenium RC servers running at all times. If one or more crashes for any reason, running the batch file again will start any that are missing. The selenium RC server will not start if its port is in use, so only the ones missing will run, and you’ll have them all up and running again.

Ok, what about the client side? I don’t want to have to edit another file in my development environment.

On the client side, we are using phpunit with Testing_Selenium. Of course all of our selenium test classes extend a parent class, so it was easy enough for us to create some dynamic logic there to decide which port to use.

<?php
class SeleniumTestHelper
{
    public function setup()
    {
        $ports = array(user1=> 4444,
                       ‘user2=> 4445,
                       ‘user3=> 4446,
                       ‘user4=> 4447);
        $user = someFunctionThatDeterminesUser();
        define(BROWSER‘, ‘*firefox);
        define(URL‘, ‘http://www.example.com);
        define(SERVER‘, ‘192.168.0.2);
        define(PORT‘, $ports[$user]);
        $this->selenium = new Testing_Selenium(BROWSER, URL, SERVER, PORT);
    }
}
?>

HTML code generated by vim-color-improved v.0.3.2.

PHP Mail Class

February 3rd, 2008

This is a very simple mailer class that is also easy to use.

<?php
/**
 * mail.php
 *
 * A (very) simple mailer class written in PHP.
 *
 * @author Zachary Fox
 * @version 1.0
 */

class ZFmail{
    var $to = null;
    var $from = null;
    var $subject = null;
    var $body = null;
    var $headers = null;

     function ZFmail($to,$from,$subject,$body){
        $this->to      = $to;
        $this->from    = $from;
        $this->subject = $subject;
        $this->body    = $body;
    }

    function send(){
      $this->addHeader(From: .$this->from."\r\n");
        $this->addHeader(Reply-To: .$this->from."\r\n");
        $this->addHeader(Return-Path: .$this->from."\r\n");
        $this->addHeader(X-mailer: ZFmail 1.0."\r\n");
        mail($this->to,$this->subject,$this->body,$this->headers);
    }

    function addHeader($header){
        $this->headers .= $header;
    }

}
?>

HTML code generated by vim-color-improved v.0.3.2.

Usage

Using the mail class is easy. Simply create a new ZFmail object, passing the parameters $to,$from,$subject, and $body, then call the method send on the object that you created. It’s as easy as pie. The following example is for a simple form mail script.

Example

<?php
/**
 * example/mail.php
 *
 * An example script to accept a post and send an email using ZFmail.
 *
 * @author Zachary Fox
 */

 // Include the mail.php file that holds the class definition
 require_once(mail.php);

 // First we set the to address. I would not let anyone put in a to 
 // address in a web form, and neither should you.
 $to =me@example.com‘;

 // Then we get the information we need from the $_POST array.
 // This step is not necessary, but in a production environment, 
 // we would process and sanitize this data here, rather than 
 // passing raw post data to the class.
 $from = $_POST['from'];
 $subject = $_POST['subject'];
 $body = $_POST['body'];

 // Then create the ZFmail object using the information from above
 $mail = new ZFmail($to,$from,$subject,$body);

 // Finally, call the object’s send method to deliver the mail.
 $mail->send();
?>

HTML code generated by vim-color-improved v.0.3.2.

Vim Color Improved - Syntax Highlighting for WordPress

January 8th, 2008

Vim Color Improved is a syntax highlighting plugin that allows you to include code from local or remote files in your Wordpress posts. I started using vim to syntax highlight my code samples based on a couple of searches that turned up this page here. However, since I started my new project that involves posting even more code, I thought it’s about time to come up with another solution. The only other vim highlighting plugin that I found was old, required a Perl library from cpan, and didn’t seem to work in the version of WordPress I’m running here. So I set out to create my own.

Download Vim Color Improved

It uses the same tag and parameter parsing as the popular codeviewer 1.4, and should be compatible with it’s options. In addition, any of the optional parameters from codeviewer 1.4 can be set as defaults, which can then be overriden by parameters in the tag. Vim Color Improved outputs code in <pre> formatted blocks, rather than ordered lists, which can be difficult to copy and paste, and can syntax highlight any language which vim supports.

Vim Color Improved contains a sophisticated caching system that stores the generated html to the filesystem. This greatly reduces the time required to display the code. In addition, it checks the modified time on both local and remote files to ensure that cached information is up-to-date. If it is unable to access the source code, and there is a cached version available, it will display the cached version with a notice.

Using Vim Color Improved

(These instructions basically parallel those for CodeViewer 1.4)

Vim Color Improved searches your post for a custom tag named [viewcode ] [/viewcode], that tells the server to look at an external file and parse it into syntax higihlighted html. It can be placed anywhere a block-level tag is valid but the tag must be properly closed.

Note that there should not be a white space character after viewcode and before ].

Parameters
[viewcode ] src=”URI or path to local file” link=yes|no lines= scroll=yes|no scrollheight=valid css height showsyntax=yes|no cache=yes|no[/viewcode]

Default values for all of these parameters, other than src can be set in the options page.

The src attribute is required.
src - string - The URI or path to a local file of the code to display. Note that relative paths are in relation to the default_path set in the options page. This default value is set to the directory your blog is installed in.

The link attribute is optional.
link - string - Should the link to the code be displayed (yes), or not be displayed (no). If the link attribute is left out of the tag completely, the value defaults to no.

The lines attribute is optional.
lines - string - Which line numbers shall be visible in the output. Use , and - to separate line numbers. Example: lines=1,3-5,10-12,16-18,22.

The scroll attribute is optional.
scroll - string - Should the scrollbar be displayed (yes), or not be displayed (no).

The scrollheight attribute is optional.
height- string - Height of the scrollbar. Any valid css height declaration can be used. Example: 100px or 50em

The showsyntax attribute is optional.
showsyntax - string - Should the syntax used of [viewcode ] be displayed (yes), or not be displayed (no).

All attribute values can optionally be surrounded with double quotes (”) or single quotes(’).

Installation

  1. Download vim-color-improved-0.3.2.zip.
  2. Unzip the archive and copy the entire vim-color-improved folder to the wp-content/plugins directory
  3. Vim Color Improved needs a directory to store the cached files and to use as a temp directory. Please make sure that your web server can write to and read from the vim-color-improved/tmp directory.
  4. Activate the plugin from the Plugins page in your WordPress administration console.
  5. Vim Color Improved also provides an options page for you to set the default options. While the plugin will work without any intervention, you may wish to review these at (Options->Vim Color Improved. You may also see a list of cached files and clear the cache there.

Frequently Asked Questions

Why are there no FAQs?

This is the first release.

Example

Here is an example of Vim Color Improved in action. We can see here the parameters that were passed in the tag by looking at the showsyntax block above the html code block.

[viewcode]src=http://www.zacharyfox.com/blog/wp-content/plugins/vim-color-improved/style.css cache=yes showsyntax=yes[/viewcode]

pre.vci_code{
        background:#333;
        color:#fff;
        padding:5px;
        font-size:12px;
        margin-bottom:0;
        margin-top:0;
}

p.vci_info, p.vci_warning{
        background:#eee;
        color:#666;
        font-size:80%;
        padding:3px;
        margin-top:0;
        margin-bottom:0;
        text-align:right;
}

p.vci_warning{
        background:#fee;
        font-weight:bold;
        text-align:left;
}

HTML code generated by vim-color-improved v.0.3.2.

Requirements

This plugin may not work on all php installations. Specifically, there are some access needs that may be locked down on your web server.

  1. Your web server must be able to exec(vim) through php
  2. If you want to use remote files, your web server must be able to open the files through http using file()

To Do List

  1. Add the ability to use vim’s options, such as using css, using xhtml, etc…
  2. Add the ability to use WYSIWYG editor for posts, including file selection box for local files.

Version History

v.0.3.2 First Public Version

License

Copyright 2008 Zachary Fox (email : ecommerceninja at gmail dot com)

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA

Fibonacci in Java

January 6th, 2008

So we’ve seen lots of examples of our Fibonacci program in scripting languages, but other than C, I haven’t touched on many compiled languages. So here is a version in Java, probably one of the most common and popular languages in use today. Considered by advocates to be the among the best enterprise application development languages, we’ll see here how to write our simple program.

/*
 * Much like C’s stdio.h, the java.io.* classes will let us access stdin and stdout.
 */

import java.io.*;

/*
 * Like Ruby, in java, everything is an object. To write a program, you’ll need to
 * start by declaring a class. As in C, our program execution starts with the main
 * function. Also like C, Java is a compiled language, so you’ll need to compile 
 * the code and then run the class using the java interpreter.
 */

class Fibonacci {

  /*
   * So here we are defining the main function. Remember that this is supposed to
   * actually run this program, so the function needs to be `public`, in addition,
   * it’s `static`, meaning we can call this method without an object of the Fibonacci
   * class being instantiated, and it doesn’t need to return anything, as it will
   * run by the interpreter, which will handle the exit status. 
   */

  public static void main(String args[]) {

    /* 
     * We are using System.out.println here, but newer versions of Java have the printf method.
     */

    System.out.println("How many numbers of the sequence would you like?");

    /*
     * I’m sure there’s more than one way to skin a cat, but to read stdin here, we
     * are creating a new BufferedReader, which will read one line of input.
     */

    InputStreamReader sr = new InputStreamReader(System.in);
    BufferedReader br    = new BufferedReader(sr);

    /*
     * Now here is a concept we haven’t addressed yet. The java compiler complains if
     * you try to call a method that could throw an exception (error), so I’ve included
     * an example here of how to handle the exceptions that could be thrown. Also, like
     * in our previous examples, we are casting the input to an integer.
     */

    try {
      String input = br.readLine();
      int n = Integer.valueOf(input).intValue();
      fibonacci(n);
    } catch (NumberFormatException e){
      System.out.println("That is not an integer. Please enter an integer value");
    } catch (IOException e) {
      System.out.println("I did not recieve an input");
    }
  }

  /*
   * So here is our Fibonacci function. like the main function, it is public and can be
   * called without creating a Fibonacci object. We’ve also introduced a new method of 
   * calculating the sequence without using a temporary variable. In a later post, I will
   * examine the different algorithms used to calculate the Fibonacci sequence, and compare
   * performance in multiple languages.
   */

  public static void fibonacci(int n){
    int a=0,b=1;

    for (int i=0;i<n;i++){
      System.out.println(a);
      a=a+b;
      b=a-b;
    }
  }
}

HTML code generated by vim-color-improved v.0.3.2.Download this code: fibonacci.java

Fibonacci in Ruby

January 5th, 2008

So finally we get to Ruby. Is it a ghetto? I don’t know about that, but I do know that writing our simple Fibonacci program in Ruby was a piece of cake. Before we get to the good stuff, though, I’d like to recap where we are, and what we’ve done so far. Here’s a list of the Fibonacci project programs so far:

So this is our sixth version of the simple sequence generator, this time in Ruby

#!/usr/local/bin/ruby

# In Ruby, we define a function with def…end functions can accept parameters,
# but don’t have to, and you can leave off the parenthesis if your function does
# not need them.

def main
  printf "\nHow many numbers of the sequence would you like?\n"

  # Here, STDIN is a constant, but like everything in Ruby, it’s also a class, so
  # we use the readline method to get our input. to_i casts our input to an integer

  n = STDIN.readline.to_i
  fibonacci(n)
end

# Here is a good example of something that is cool about Ruby. The times method
# works just like it sounds, it will do something n times. As in Perl and Python,
# we don’t need a temp variable here to swap the values for a and b.

def fibonacci(n)
  a,b = 0,1
  n.times do
    printf("%d\n", a)
    a,b = b,a+b
  end
end

main

HTML code generated by vim-color-improved v.0.3.2.Download this code: fibonacci.rb

The next installment will be another popular language. Stay tuned to see Fibonacci in Java.

Fibonacci in Python

January 5th, 2008

In our latest installment of the Fibonacci project, we’ll write our simple program in Python. For those of you who are unfamiliar with what we are doing here, please read the first post here. Python is a newer, but increasingly popular scripting language. I suppose the most interesting difference here is that Python is dependent on indentation to define blocks, rather than braces or other language constructs.

#!/usr/bin/python

# Import the system library. This allows us to access stdin later.
import sys

# Here’s our main function. Python is pretty efficient here. You
# should notice that there are no braces. Python is dependant on
# whitespace to define blocks.

def main():
  print "\nHow many numbers of the sequence would you like?"
  n = int(sys.stdin.readline())
  fibonacci(n)

# Here’s the fibonacci function. Like in Perl, you can assign multiple
# variables on a line without using a temporary variable. Also, the for 
# loop here works more like a foreach loop by setting a range from 0 to n.

def fibonacci(n):
  a,b = 0,1
  for i in range(0,n):
    print a
    a,b, = b,a+b

main()

HTML code generated by vim-color-improved v.0.3.2.

Fibonacci in Perl

January 3rd, 2008

So this is our fourth post of the Fibonacci project, and in this installment, we are going to take on Perl. For those of you who don’t know about the Fibonacci project, you should read the first post, Fibonacci in C. Also, you may want to check out the other posts in the series. The comments in the code will make more sense if you have seen the other examples.

#!/usr/bin/perl

# Functions in Perl are called subroutines. Like bash, you don’t define the 
# parameters in the function declaration. We’ll see how to access the parameters
# when we look at the Fibonacci subroutine below.

sub main {

# Again, the ubiquitous printf function. Apparently a staple of programming
printf "\nHow many numbers of the sequence would you like?\n";

# Once again, we don’t need to declare variables before using them.
# Perl’s scalar variables, prefaced with $, can be either strings or numbers
# We use <STDIN> to get the data from stdin here

$n = <STDIN>;

# As in PHP, we need to remove the newline at the end

chop $n;

&fibonacci($n);

exit 0;
}

# Except for the first line declaring the subroutine, and the different way that
# parameters passed to the subroutine are passed, this is identical to the PHP version

sub fibonacci {
  $a = 0;
  $b = 1;

  # So now we see the parameter being used here. For clarity, I have written the for
  # loop using $n like the other examples. To set $n using the first parameter passed
  # to the subroutine, I access the scalar variable $_[0], which is the first element
  # of the parameter array @_

  $n = $_[0];

  for ($i=0;$i<$n;$i++){
    printf "%d\n", $a;
    $sum = $a + $b;
    $a = $b;
    $b = $sum;
  }
}

&main;

HTML code generated by vim-color-improved v.0.3.2.Download this code: fibonacci.pl

Any Perl gurus want to critique my work here? Like most of the examples, this is a simplified version, but one that works.

Fibonacci in BASH

January 3rd, 2008

So here’s the big surprise. Shell scripting! It’s not what most people think of when they think of programming, but systems administrators are still doing lots of scripting work to automate tasks. Shell scripting can tackle some pretty serious and complicated problems, so running our Fibonacci program is no sweat. If you haven’t seen the Fibonacci in C and the Fibonacci in PHP, now might be a good time to review them.

#!/bin/bash

#
# Here is our main function. Like PHP, I could have simply placed this in the script
# rather than having a function. You notice that like C and PHP, the printf function
# still exists. Unlike C and PHP function calls do not enclose the parameters with 
# paraenthsis.

function main {
  printf "\nHow many numbers of the sequence would you like?\n"

  # Bash lets us use a function "read" to get input from stdin
  # Notice that we are not using a dollar sign in front of the variables when
  # we set them, but we need to when we use them.

  read n
  fibonacci $n

  # Again, I’m exiting with status 0

  exit 0
}

# Starting to look familiar? This function is actually a little different than the 
# C style for loop that we’ve used before. Instead we use while..do..done to accomplish
# the same thing. You’ll also see that rather than specifying parameters in the 
# function;s declaration, we simply reference the variable "$1" to get the first parameter
# passed when the function was called.

function fibonacci {
  a=0
  b=1
  i=0

  while [ $i -lt $1 ]
  do
    printf "%d\n" $a
    let sum=$a+$b
    let a=$b
    let b=$sum
    let i=$i+1
  done
}

main

HTML code generated by vim-color-improved v.0.3.2.Download this code: fibonacci.sh

So what are the gotchas for scripting in BASH? What killed me is whitespace! (a=1 is not the same as a = 1). Once you get the hang of it, it’s not a big deal, but if you are used to working in PHP or another language that ignores whitespace, you’ll run through a few syntax errors before figuring it out. Using an editor like Vim that has syntax highlighting will help a lot there.So there is the third version of our Fibonacci project. Coming soon, I’ll take on the popular scripting languages perl, python, and ruby.

Fibonacci in PHP

January 3rd, 2008

So here is my second post in the Fibonacci project. For those of you that have not seen the first post here, the Fibonacci project is a learning experiment designed to highlight the similarities and differences between programming languages. In our C Fibonacci example, we learned that we need to declare variables and types, even the return type of a function. In this PHP example, we’ll see that PHP, while different, is very similar to C in syntax.

#!/usr/bin/php -q

<?php
/**
 * This is our main function. In PHP, there isn’t really a need for this to be
 * a function, but to keep consistant, I’ve placed it there anyway, and called
 * it from the script. In keeping with good programming practices, this script
 * exits with a status 0. Any other status would indicate an error condition.
 */

function main(){

  printf("How many numbers of the sequence would you like?\n");

  /*
   * To read from stdin in php, you open it as a file handle, and use
   * the standard file reading functions
   */

  $fr=fopen("php://stdin","r");
  $n = rtrim(fgets($fr,128));
  fclose ($fr);

  /* Then we call the fibonacci function */
  fibonacci($n);
  exit(0);
}

/**
 * The fibonacci function should look familiar.
 */

function fibonacci($n){
  /* 
   * Notice that in PHP, we do not have to declare our variables, nor must we
   * declare their types. Also see how variables in PHP are prefaced with the 
   * dollar sign. Other than that, this is identical to the C version of this function.
   */
  $a = 0;
  $b = 1;
  for ($i = 0; $i < $n; $i++){
    printf("%d\n",$a);
    $sum = $a+$b;
    $a = $b;
    $b = $sum;
  }
}

/**
 * In PHP, program execution starts here. It isn’t neccessary to place functions 
 * ahead of the program, but it’s a good practice. In a larger application, these
 * functions would be in seperate files. Again, since PHP is a procedural language,
 * I could have simply included the contents of the main function here, rather than
 * defining a function and calling it.
 */

main();

?>

HTML code generated by vim-color-improved v.0.3.2.Download this code: fibonacci.php

You’ll notice a couple of things about this version of the Fibonacci program. Because it’s intended to be run on the command line, the first line tells the shell which interpretor to use. In addition, I have been careful here to return an exit code so that the shell knows that the program completed successfully.Stay tuned for our next installment, I’ll keep it a surprise, and even though everyone thinks it will be Ruby, I’m going to save that one for later.

Fibonacci in C

January 3rd, 2008

Welcome to the first post of the Fibonacci project. In the following weeks, I am going to write this simple program in as many languages as possible, to highlight the similarities and differences between them. Today I will start with C, a classic language that is still in use today, and a good foundation for everything else that we will see. Rather than writing a lengthy post with each language, I’ll try to comment the code to point out the important things. Hopefully, this learning experiment will teach me something, and hopefully it will provide a handy resource for people to compare languages, even if it’s in a limited capacity.

So before I started, I gave myself the following “spec sheet” for writing the code:

The purpose of the Fibonacci project is to create a simple programming example in as many languages as possible, to provide a clear demonstration of the differences and similarities between them.

The sample code should:

  • Accept an input “x” (A value to progress up to)
  • Starting at 0 and 1, output the Fibonacci sequence up to “x” permutations.
  • There should be two functions, for clarity.
    • (main) Accepts the input and calls the fibonacci function.
    • (fibonacci) One that accepts the value of x and outputs the sequence.

The code should accept input from the console (stdin), with a prompt, and output to the console (stdout). This is so we keep everything simple. All of the code should be thoroughly commented.

/**
 * You’ll notice that we need to include a header file that
 * contains functions we need to use. Being a compiled language,
 * it’s inefficient to include functions that aren’t needed.
 * stdio.h contains functions for reading from and writing to the console
 */

#include <stdio.h>

/**
 * In C, the program executes the main function. You should also take note
 * that we must declare a return type for the function. In this case, it’s
 * an integer, and we return 0 to indicate successful completion of the 
 * program.
 */

int main ()
{
  /* Notice that we need to declare our variables, and their type */

  int n;

  /* printf prints a formated string to the stdout */

  printf("\nHow many numbers of the sequence would you like?\n");

  /* scanf reads a formated string from the stdin. We are expecting an integer here. */

  scanf("%d",&n);

  /* Here we call the fibonacci function */

  fibonacci(n);

  /* Finally, return 0 */

  return 0;
}

/**
 * This is the simple fibonacci sequence generator. Notice also, we
 * declare the type of variable we expect to be passed to the function.
 */

int fibonacci(int n)
{
  /**
   * Here we declare and set our variables.
   */
  int a = 0;
  int b = 1;
  int sum;
  int i;

  /**
   * Here is the standard for loop. This will step through, performing the code
   * inside the braces until i is equal to n.
   */
  for (i=0;i<n;i++)
  {
    printf("%d\n",a);
    sum = a + b;
    a = b;
    b = sum;
  }
  return 0;
}

HTML code generated by vim-color-improved v.0.3.2.Download this code: fibonacci.c

So there’s my version of the Fibonacci sequence generator in C. I’m sure there are some problems with it, but the above code works. What would you change to make it better? Stay tuned for the next installment … PHP.