MDL-48766 lib: Import MaxMind GeoIP2 PHP API
[moodle.git] / iplookup / tests / geoip_test.php
CommitLineData
64b0f3ab
PS
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.
13//
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/>.
16
17/**
18 * GeoIP tests
19 *
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
24 */
25
26defined('MOODLE_INTERNAL') || die();
27
28
29/**
30 * GeoIp data file parsing test.
31 */
8252b7c2 32class core_iplookup_geoip_testcase extends advanced_testcase {
64b0f3ab
PS
33
34 public function test_geoip() {
35 global $CFG;
36 require_once("$CFG->libdir/filelib.php");
37 require_once("$CFG->dirroot/iplookup/lib.php");
38
39 if (!PHPUNIT_LONGTEST) {
40 // this may take a long time
41 return;
42 }
43
44 $this->resetAfterTest();
45
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);
52 }
53
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);
56 }
57
58 $this->assertTrue(file_exists($gzfile));
59
60 $zd = gzopen($gzfile, "r");
61 $contents = gzread($zd, 50000000);
62 gzclose($zd);
63
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);
69
70 $this->assertTrue(file_exists($geoipfile));
71
72 $CFG->geoipfile = $geoipfile;
73
74 $result = iplookup_find_location('147.230.16.1');
75
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]);
84 }
85}
86