4

I'm doing some basic unit testing on a utility function I made years ago but it involves accessing the $_SERVER array.

Since my unit tests are run from the command line, I have to manually set the values of the array myself.

This works well using GitLab Runners because on the .gitlab-ci.yml file I just do something like:

before_script:
  - export SERVER_PORT="80"
  - export SERVER_NAME="gitlab"

My test is currently unable to test all statements from that function as it checks for the $_SERVER['SERVER_NAME'] value.

Unit Test

public function testGetEnvironment() {
    shell_exec('set SERVER_NAME="localhost"');
    $this->assertEquals("localhost", $this->util->get_environment());

    shell_exec('set SERVER_NAME="gitlab"');
    $this->assertEquals("gitlab", $this->util->get_environment());
}

NOTE: I had to use set as I am on a Windows machine while our GitLab Runner is on a Linux machine so I used export on the gitlab-ci.yml file.

I was expecting this test to pass but it seems like the command to set the environment variable using shell_exec isn't changing the value at all. I still get the value from what was defined from the YAML file.

Update

Here's the failure message:

1) UtilTest::testGetEnvironment
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-'localhost'
+'gitlab'
Mureinik
  • 297,002
  • 52
  • 306
  • 350
dokgu
  • 4,957
  • 3
  • 39
  • 77

1 Answers1

4

Any shell command you execute would be a separate process and wouldn't affect the running process. Since you're unit testing how the function would use the $_SERVER variable, you don't need to go through all the hassle of thinking how it would be set in a "real" scenario - just manually modify it and test your function:

public function testGetEnvironment() {
    $_SERVER["SERVER_NAME"] = "localhost";
    $this->assertEquals("localhost", $this->util->get_environment());

    $_SERVER["SERVER_NAME"] = "gitlab";
    $this->assertEquals("gitlab", $this->util->get_environment());
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350