cbaykam's avatar

How to mock the clients Ip address

Hi ;

I am testing a Laravel 5.1 application which finds the user's location from his / her ip address. The problem is when running tests all the requests seems to come from 127.0.0.1, how can I mock that ip address to test that function ?

0 likes
9 replies
JillzTom's avatar

If you are the one trying to access the app, you'll always get 127.0.0.1 as the ip address, because you're running on a localhost machine. You'll have to load it into a server to get the different IP's.

//FOR PRODUCTION or SERVER, USE THIS LINE
 $ip = $_SERVER['REMOTE_ADDR'];

//FOR LOCALHOST, USE THIS LINE
$ip = 'xxx.xxx.xxx.xxx'; // replace this with your IP address. 
cbaykam's avatar

thanks for the reply, but isn't it possible to produce fake requests with custom ip without changing the actual logic in the application ?

iamfaiz's avatar

You can create a dedicated class, something like:

class UserIpAddress
{
    public function get()
    {
        return $_SERVER['REMOTE_ADDR'];
    }
}

And then while testing swap it using Laravel's service container or maybe using mockery. You can even mock the Laravel's Request class if you are using that.

pmall's avatar

Can you explain more what you want to do ? Because if you want to use the ip address somewhere you can just put it in a variable and change it.

bashy's avatar

You can fake it but you won't be able to see the response because of the TCP three-way-handshake.

You may be able to use X-Forwarded-For HEADER but reading the Symfony docs, you have to allow it via setTrustedProxies()

wiseArtisans's avatar
$this->call('POST', 'api/xyz_path', ['data'=>'value'], [], [], ['REMOTE_ADDR' => '10.1.0.1']);

$this->request->getClientIp() will return '10.1.0.1' instead of '127.0.0.1'

8 likes
nikola.barac's avatar

Just to correct alex_giuvara's answer, the $server vars come at the 5th place:

$this->call('POST', 'api/xyz_path', ['data'=>'value'], [], ['REMOTE_ADDR' => '10.1.0.1']);
12 likes
kevmul's avatar

If you are using the helper $this->post you can use this as the third param

$this->post('api/xyz_path', ['data'=>'value'], ['REMOTE_ADDR' => '10.1.0.1']);
10 likes
AnnaD's avatar

Now inside a Test you can also use:

$this->withServerVariables(['REMOTE_ADDR' => '10.1.0.1']);
9 likes

Please or to participate in this conversation.