dextervip
dextervip

Reputation: 5069

Override environment variable when running on Jenkins

I'm testing a Zend Framework application using PHPUnit and Jenkins. I need to override the APPLICATION_ENV environment variable which is access using PHP's getenv in the PHPUnit bootstrap.php file:

<?php

// Define application environment
defined('APPLICATION_ENV')
|| define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'testing'));

... use APPLICATION_ENV to pick database, configuration, etc. ...

I have two environments: testing (for local machines) and testing-ci (for Jenkins machine). How can I set the variable to testing-ci when it runs in Jenkins? Is there any way to set it in build.xml for Ant or Phing?

Upvotes: 6

Views: 6147

Answers (2)

David Harkness
David Harkness

Reputation: 36562

Step 1: Add the environment variables to Jenkins.

Open either the global or project-specific configuration page depending on your needs and scan down for the Environment variables section. Check the checkbox and use the Add button to add key/value pairs.

These will be passed by Jenkins to your Ant build script.

Step 2: Load them into Ant.

Near the top of your Ant build.xml script, load all environment variables with an env prefix so they don't interfere with other properties.

<property environment="env"/>

Now all imported variables will be available using the env prefix, e.g. ${env.HOME}.

Step 3: Pass them to PHPUnit.

Assuming you're using the <exec> task to run PHPUnit, you can pass each needed variable to it using the <env> child element.

<exec taskname="test" executable="phpunit">
    <env key="APPLICATION_ENV" value="${env.APPLICATION_ENV}"/>
    ...
</exec>

Note: You might want to try just the first step to see if Ant will pass the environment variables along to executed child processes, but I think the other two steps are good for making it clear what is required to other developers.

Upvotes: 7

Theodore R. Smith
Theodore R. Smith

Reputation: 23259

OK.

Here's what you do...

First, create a new file called bootstrap.php.

Next, in boostrap.php, put the following code:

if (!empty($argv) && 
    ($key = array_search('--environment', $argv)) !== FALSE)
{
    $env = $argv[$key + 1];
    putenv('APPLICATION_ENV=' . $env);
}

Load the bootstrap.php into your testsuite or (even better) phpunit.xml.

Finally, via your CI build config, or via the console or wherever, execute your unit tests like phpunit UnitTest.php --environment dev.

You're good to go.

Upvotes: 0

Related Questions