Merge branch 'MDL-47037-27' of git://github.com/jethac/moodle into MOODLE_27_STABLE
[moodle.git] / iplookup / tests / geoip_test.php
blob3c21394c4e31a7e762cfb10e2baaf036f7d87b03
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * GeoIP tests
20 * @package core_iplookup
21 * @category phpunit
22 * @copyright 2012 Petr Skoda {@link http://skodak.org}
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 defined('MOODLE_INTERNAL') || die();
29 /**
30 * GeoIp data file parsing test.
32 class core_iplookup_geoip_testcase extends advanced_testcase {
34 public function test_geoip() {
35 global $CFG;
36 require_once("$CFG->libdir/filelib.php");
37 require_once("$CFG->dirroot/iplookup/lib.php");
39 if (!PHPUNIT_LONGTEST) {
40 // this may take a long time
41 return;
44 $this->resetAfterTest();
46 // let's store the file somewhere
47 $gzfile = "$CFG->dataroot/phpunit/geoip/GeoLiteCity.dat.gz";
48 check_dir_exists(dirname($gzfile));
49 if (file_exists($gzfile) and (filemtime($gzfile) < time() - 60*60*24*30)) {
50 // delete file if older than 1 month
51 unlink($gzfile);
54 if (!file_exists($gzfile)) {
55 download_file_content('http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz', null, null, false, 300, 20, false, $gzfile);
58 $this->assertTrue(file_exists($gzfile));
60 $zd = gzopen($gzfile, "r");
61 $contents = gzread($zd, 50000000);
62 gzclose($zd);
64 $geoipfile = "$CFG->dataroot/geoip/GeoLiteCity.dat";
65 check_dir_exists(dirname($geoipfile));
66 $fp = fopen($geoipfile, 'w');
67 fwrite($fp, $contents);
68 fclose($fp);
70 $this->assertTrue(file_exists($geoipfile));
72 $CFG->geoipfile = $geoipfile;
74 $result = iplookup_find_location('147.230.16.1');
76 $this->assertEquals('array', gettype($result));
77 $this->assertEquals('Liberec', $result['city']);
78 $this->assertEquals(15.0653, $result['longitude'], '', 0.001);
79 $this->assertEquals(50.7639, $result['latitude'], '', 0.001);
80 $this->assertNull($result['error']);
81 $this->assertEquals('array', gettype($result['title']));
82 $this->assertEquals('Liberec', $result['title'][0]);
83 $this->assertEquals('Czech Republic', $result['title'][1]);