Per wikitech-l discussion: Move tests from maintenance/tests/ to tests/. They're...
[lhc/web/wiklou.git] / maintenance / tests / phpunit / includes / api / RandomImageGenerator.php
1 <?php
2
3 /*
4 * RandomImageGenerator -- does what it says on the tin.
5 * Requires Imagick, the ImageMagick library for PHP, or the command line equivalent (usually 'convert').
6 *
7 * Because MediaWiki tests the uniqueness of media upload content, and filenames, it is sometimes useful to generate
8 * files that are guaranteed (or at least very likely) to be unique in both those ways.
9 * This generates a number of filenames with random names and random content (colored circles)
10 *
11 * It is also useful to have fresh content because our tests currently run in a "destructive" mode, and don't create a fresh new wiki for each
12 * test run.
13 * Consequently, if we just had a few static files we kept re-uploading, we'd get lots of warnings about matching content or filenames,
14 * and even if we deleted those files, we'd get warnings about archived files.
15 *
16 * This can also be used with a cronjob to generate random files all the time -- I use it to have a constant, never ending supply when I'm
17 * testing interactively.
18 *
19 * @file
20 * @author Neil Kandalgaonkar <neilk@wikimedia.org>
21 */
22
23 /**
24 * RandomImageGenerator: does what it says on the tin.
25 * Can fetch a random image, or also write a number of them to disk with random filenames.
26 */
27 class RandomImageGenerator {
28
29 private $dictionaryFile;
30 private $minWidth = 400;
31 private $maxWidth = 800;
32 private $minHeight = 400;
33 private $maxHeight = 800;
34 private $circlesToDraw = 5;
35 private $imageWriteMethod;
36
37 public function __construct( $options ) {
38 global $wgUseImageMagick, $wgImageMagickConvertCommand;
39 foreach ( array( 'dictionaryFile', 'minWidth', 'minHeight', 'maxHeight', 'circlesToDraw' ) as $property ) {
40 if ( isset( $options[$property] ) ) {
41 $this->$property = $options[$property];
42 }
43 }
44
45 // find the dictionary file, to generate random names
46 if ( !isset( $this->dictionaryFile ) ) {
47 foreach ( array( '/usr/share/dict/words', '/usr/dict/words' ) as $dictionaryFile ) {
48 if ( is_file( $dictionaryFile ) and is_readable( $dictionaryFile ) ) {
49 $this->dictionaryFile = $dictionaryFile;
50 break;
51 }
52 }
53 }
54 if ( !isset( $this->dictionaryFile ) ) {
55 throw new Exception( "RandomImageGenerator: dictionary file not found or not specified properly" );
56 }
57
58 // figure out how to write images
59 if ( class_exists( 'Imagick' ) ) {
60 $this->imageWriteMethod = 'writeImageWithApi';
61 } elseif ( $wgUseImageMagick && $wgImageMagickConvertCommand && is_executable( $wgImageMagickConvertCommand ) ) {
62 $this->imageWriteMethod = 'writeImageWithCommandLine';
63 } else {
64 throw new Exception( "RandomImageGenerator: could not find a suitable method to write images" );
65 }
66 }
67
68 /**
69 * Writes random images with random filenames to disk in the directory you specify, or current working directory
70 *
71 * @param $number Integer: number of filenames to write
72 * @param $format String: optional, must be understood by ImageMagick, such as 'jpg' or 'gif'
73 * @param $dir String: directory, optional (will default to current working directory)
74 * @return Array: filenames we just wrote
75 */
76 function writeImages( $number, $format = 'jpg', $dir = null ) {
77 $filenames = $this->getRandomFilenames( $number, $format, $dir );
78 foreach( $filenames as $filename ) {
79 $this->{$this->imageWriteMethod}( $this->getImageSpec(), $format, $filename );
80 }
81 return $filenames;
82 }
83
84 /**
85 * Return a number of randomly-generated filenames
86 * Each filename uses two words randomly drawn from the dictionary, like elephantine_spatula.jpg
87 *
88 * @param $number Integer: of filenames to generate
89 * @param $extension String: optional, defaults to 'jpg'
90 * @param $dir String: optional, defaults to current working directory
91 * @return Array: of filenames
92 */
93 private function getRandomFilenames( $number, $extension = 'jpg', $dir = null ) {
94 if ( is_null( $dir ) ) {
95 $dir = getcwd();
96 }
97 $filenames = array();
98 foreach( $this->getRandomWordPairs( $number ) as $pair ) {
99 $basename = $pair[0] . '_' . $pair[1];
100 if ( !is_null( $extension ) ) {
101 $basename .= '.' . $extension;
102 }
103 $basename = preg_replace( '/\s+/', '', $basename );
104 $filenames[] = "$dir/$basename";
105 }
106
107 return $filenames;
108
109 }
110
111
112 /**
113 * Generate data representing an image of random size (within limits),
114 * consisting of randomly colored and sized circles against a random background color
115 * (This data is used in the writeImage* methods).
116 * @return {Mixed}
117 */
118 public function getImageSpec() {
119 $spec = array();
120
121 $spec['width'] = mt_rand( $this->minWidth, $this->maxWidth );
122 $spec['height'] = mt_rand( $this->minHeight, $this->maxHeight );
123 $spec['fill'] = $this->getRandomColor();
124
125 $diagonalLength = sqrt( pow( $spec['width'], 2 ) + pow( $spec['height'], 2 ) );
126
127 $draws = array();
128 for ( $i = 0; $i <= $this->circlesToDraw; $i++ ) {
129 $radius = mt_rand( 0, $diagonalLength / 4 );
130 $originX = mt_rand( -1 * $radius, $spec['width'] + $radius );
131 $originY = mt_rand( -1 * $radius, $spec['height'] + $radius );
132 $perimeterX = $originX + $radius;
133 $perimeterY = $originY + $radius;
134
135 $draw = array();
136 $draw['fill'] = $this->getRandomColor();
137 $draw['circle'] = array(
138 'originX' => $originX,
139 'originY' => $originY,
140 'perimeterX' => $perimeterX,
141 'perimeterY' => $perimeterY
142 );
143 $draws[] = $draw;
144
145 }
146
147 $spec['draws'] = $draws;
148
149 return $spec;
150 }
151
152
153 /**
154 * Based on an image specification, write such an image to disk, using Imagick PHP extension
155 * @param $spec: spec describing background and circles to draw
156 * @param $format: file format to write
157 * @param $filename: filename to write to
158 */
159 public function writeImageWithApi( $spec, $format, $filename ) {
160 $image = new Imagick();
161 $image->newImage( $spec['width'], $spec['height'], new ImagickPixel( $spec['fill'] ) );
162
163 foreach ( $spec['draws'] as $drawSpec ) {
164 $draw = new ImagickDraw();
165 $draw->setFillColor( $drawSpec['fill'] );
166 $circle = $drawSpec['circle'];
167 $draw->circle( $circle['originX'], $circle['originY'], $circle['perimeterX'], $circle['perimeterY'] );
168 $image->drawImage( $draw );
169 }
170
171 $image->setImageFormat( $format );
172 $image->writeImage( $filename );
173 }
174
175
176 /**
177 * Based on an image specification, write such an image to disk, using the command line ImageMagick program ('convert').
178 *
179 * Sample command line:
180 * $ convert -size 100x60 xc:rgb(90,87,45) \
181 * -draw 'fill rgb(12,34,56) circle 41,39 44,57' \
182 * -draw 'fill rgb(99,123,231) circle 59,39 56,57' \
183 * -draw 'fill rgb(240,12,32) circle 50,21 50,3' filename.png
184 *
185 * @param $spec: spec describing background and circles to draw
186 * @param $format: file format to write (unused by this method but kept so it has the same signature as writeImageWithApi)
187 * @param $filename: filename to write to
188 */
189 public function writeImageWithCommandLine( $spec, $format, $filename ) {
190 global $wgImageMagickConvertCommand;
191 $args = array();
192 $args[] = "-size " . wfEscapeShellArg( $spec['width'] . 'x' . $spec['height'] );
193 $args[] = wfEscapeShellArg( "xc:" . $spec['fill'] );
194 foreach( $spec['draws'] as $draw ) {
195 $fill = $draw['fill'];
196 $originX = $draw['circle']['originX'];
197 $originY = $draw['circle']['originY'];
198 $perimeterX = $draw['circle']['perimeterX'];
199 $perimeterY = $draw['circle']['perimeterY'];
200 $drawCommand = "fill $fill circle $originX,$originY $perimeterX,$perimeterY";
201 $args[] = '-draw ' . wfEscapeShellArg( $drawCommand );
202 }
203 $args[] = wfEscapeShellArg( $filename );
204
205 $command = wfEscapeShellArg( $wgImageMagickConvertCommand ) . " " . implode( " ", $args );
206 $retval = null;
207 wfShellExec( $command, $retval );
208 return ( $retval === 0 );
209 }
210
211 /**
212 * Generate a string of random colors for ImageMagick, like "rgb(12, 37, 98)"
213 *
214 * @return {String}
215 */
216 public function getRandomColor() {
217 $components = array();
218 for ($i = 0; $i <= 2; $i++ ) {
219 $components[] = mt_rand( 0, 255 );
220 }
221 return 'rgb(' . join(', ', $components) . ')';
222 }
223
224 /**
225 * Get an array of random pairs of random words, like array( array( 'foo', 'bar' ), array( 'quux', 'baz' ) );
226 *
227 * @param $number Integer: number of pairs
228 * @return Array: of two-element arrays
229 */
230 private function getRandomWordPairs( $number ) {
231 $lines = $this->getRandomLines( $number * 2 );
232 // construct pairs of words
233 $pairs = array();
234 $count = count( $lines );
235 for( $i = 0; $i < $count; $i += 2 ) {
236 $pairs[] = array( $lines[$i], $lines[$i+1] );
237 }
238 return $pairs;
239 }
240
241
242 /**
243 * Return N random lines from a file
244 *
245 * Will throw exception if the file could not be read or if it had fewer lines than requested.
246 *
247 * @param $number_desired Integer: number of lines desired
248 * @return Array: of exactly n elements, drawn randomly from lines the file
249 */
250 private function getRandomLines( $number_desired ) {
251 $filepath = $this->dictionaryFile;
252
253 // initialize array of lines
254 $lines = array();
255 for ( $i = 0; $i < $number_desired; $i++ ) {
256 $lines[] = null;
257 }
258
259 /*
260 * This algorithm obtains N random lines from a file in one single pass. It does this by replacing elements of
261 * a fixed-size array of lines, less and less frequently as it reads the file.
262 */
263 $fh = fopen( $filepath, "r" );
264 if ( !$fh ) {
265 throw new Exception( "couldn't open $filepath" );
266 }
267 $line_number = 0;
268 $max_index = $number_desired - 1;
269 while( !feof( $fh ) ) {
270 $line = fgets( $fh );
271 if ( $line !== false ) {
272 $line_number++;
273 $line = trim( $line );
274 if ( mt_rand( 0, $line_number ) <= $max_index ) {
275 $lines[ mt_rand( 0, $max_index ) ] = $line;
276 }
277 }
278 }
279 fclose( $fh );
280 if ( $line_number < $number_desired ) {
281 throw new Exception( "not enough lines in $filepath" );
282 }
283
284 return $lines;
285 }
286
287 }