development (in)action

Functional Testing PHP SSH2 Workflows With PHPUnit and Vagrant

When $this->markTestIncomplete() just won’t do. Enter Vagrant.

To begin with the tools you will need to become familiar with at as follows:

Vagrant: http://vagrantup.com You will find many good write-ups on its installation and use. For the sake of brevity I will provide links to a few I found useful and not provide much detail on this. I suggest begining here: http://vagrantup.com/v1/docs/getting-started/index.html

PHPUnit: http://www.phpunit.de

There are four ssh2 authentication methods provided with the php ssh2 tools:

  • ssh2_auth_hostbased_file — Authenticate using a public hostkey
  • ssh2_auth_none — Authenticate as “none”
  • ssh2_auth_password — Authenticate over SSH using a plain password
  • ssh2_auth_pubkey_file — Authenticate using a public key

For my project I needed to functionally validate a workflow of uploading a file to a server utilizing ssh2_auth_password and ssh2_auth_pubkey. I need to test the following to validate my results:

  • Can I authenticate with the desired method?
  • Can I validate the fingerprint of the servers key?
  • Can I put the contents of a file to a known path on the remote server?
  • Can I validate those contents and destination filename are as expected?

To accomplish these goals I require an environment with a known public and private key this provides the fingerprint and both known keys to establish the connection without much work. For password based authentication I need an environment that will allow non-tty password based auth over ssh (this feature is generally disabled and must be changed at vagrant provisioning or you must create a image that is configured.) Not wanting to create a custom box for this case I utilize the provisioning tools built into vagrant and sed. From here it’s really a matter of writing tests and running vagrant, take a look at the gist for examples I have provided.

Example Gist https://gist.github.com/3612867

The TL;DR:

  1. Write your tests
  2. Fetch the Vagrant SSH keys
  3. Create or grab the example VagrantFIle
  4. run `vagrant init`
  5. run `vagrant up`
  6. run the tests
  7. rinse / repeat